在实际的工作中,我们可能会经常使用链表结构来存储数据,特别是嵌入式开发,经常会使用 linux 内核最经典的双向链表 list_head。

本篇文章详细介绍了 Linux 内核的通用链表是如何实现的,对于经常使用的函数都给出了详细的说明和测试用例,并且移植了 Linux 内核的链表结构,在任意平台都可以方便的调用内核已经写好的函数。建议收藏,以备不时之需!

1. 链表简介

链表是一种常用的组织有序数据的数据结构,它通过指针将一系列数据节点连接成一条数据链,是线性表的一种重要实现方式。

相对于数组,链表具有更好的动态性,建立链表时无需预先知道数据总量,可以随机分配空间,可以高效地在链表中的任意位置实时插入或删除数据。

通常链表数据结构至少应包含两个域:数据域和指针域,数据域用于存储数据,指针域用于建立与下一个节点的联系。按照指针域的组织以及各个节点之间的联系形式,链表又可以分为单链表、双链表、循环链表等多种类型。

下面分别给出这几类常见链表类型的示意图:

1.1 单链表

单链表是最简单的一类链表,它的特点是仅有一个指针域指向后继节点(next)。因此,对单链表的遍历只能从头至尾(通常是 NULL 空指针)顺序进行如何移植并使用Linux内核的通用链表(附完整代码实现) - 图1

1.2 双链表

通过设计前驱和后继两个指针域,双链表可以从两个方向遍历,这是它区别于单链表的地方。

如果打乱前驱、后继的依赖关系,就可以构成 “二叉树“;如果再让首节点的前驱指向链表尾节点、尾节点的后继指向首节点,就构成了循环链表;如果设计更多的指针域,就可以构成各种复杂的树状数据结构。

如何移植并使用Linux内核的通用链表(附完整代码实现) - 图2

双链表

1.3 循环链表

循环链表的特点是尾节点的后继指向首节点。前面已经给出了双链表的示意图,它的特点是从任意一个节点出发,沿两个方向的任何一个,都能找到链表中的任意一个数据。如果去掉前驱指针,就是单循环链表。

如何移植并使用Linux内核的通用链表(附完整代码实现) - 图3

循环链表

2. Linux 内核中的链表

上面介绍了普通链表的实现方式,可以看到数据域都是包裹在节点指针中的,通过节点指针访问下一组数据。

但是 Linux 内核的链表实现可以说比较特殊,只有前驱和后继指针,而没有数据域。链表的头文件是在 include/list.h(Linux2.6 内核)下。在实际工作中,也可以将内核中的链表拷贝出来供我们使用,就需不要造轮子了。

2.1 链表的定义

内核链表只有前驱和后继指针,并不包含数据域,这个链表具备通用性,使用非常方便。因此可以很容易的将内核链表结构体包含在任意数据的结构体中,非常容易扩展。我们只需要将链表结构体包括在数据结构体中就可以。下面看具体的代码。

如何移植并使用Linux内核的通用链表(附完整代码实现) - 图4

内核中的链表

内核链表的结构

  1. `//链表结构
  2. struct list_head
  3. {
  4. struct list_head *prev;
  5. struct list_head *next;
  6. };
  7. `

当需要用内核的链表结构时,只需要在数据结构体中定义一个struct list_head{}类型的结构体成员对象就可以。这样,我们就可以很方便地使用内核提供给我们的一组标准接口来对链表进行各种操作。我们定义一个学生结构体,里面包含学号和数学成绩。结构体如下:

  1. ` struct student
  2. {
  3. struct list_head list;//暂且将链表放在结构体的第一位
  4. int ID;
  5. int math;
  6. };
  7. `

2.2 链表的初始化

2.2.1 内核实现

  1. `#define LIST_HEAD_INIT(name) { &(name), &(name) }
  2. #define LIST_HEAD(name) \
  3. struct list_head name = LIST_HEAD_INIT(name)
  4. static inline void INIT_LIST_HEAD(struct list_head *list)
  5. {
  6. list->next = list;
  7. list->prev = list;
  8. }
  9. `

2.2.2 说明

INIT_LIST_HEADLIST_HEAD都可以初始化链表,二者的区别如下:   LIST_HEAD(stu_list) 初始化链表时会顺便创建链表对象

  1. `//LIST_HEAD(stu_list)展开如下
  2. struct list_head stu_list= { &(stu_list), &(stu_list) };
  3. `

INIT_LIST_HEAD(&stu1.stu_list) 初始化链表时需要我们已经有了一个链表对象stu1_list

我们可以看到链表的初始化其实非常简单,就是让链表的前驱和后继都指向了自己

2.2.3 举例

  1. `INIT_LIST_HEAD(&stu1.stu_list);
  2. `

2.3 链表增加节点

2.3.1 内核实现

  1. `
  2. /*
  3. * Insert a new entry between two known consecutive entries.
  4. *
  5. * This is only for internal list manipulation where we know
  6. * the prev/next entries already!
  7. */
  8. #ifndef CONFIG_DEBUG_LIST
  9. static inline void __list_add(struct list_head *new,
  10. struct list_head *prev,
  11. struct list_head *next)
  12. {
  13. next->prev = new;
  14. new->next = next;
  15. new->prev = prev;
  16. prev->next = new;
  17. }
  18. #else
  19. extern void __list_add(struct list_head *new,
  20. struct list_head *prev,
  21. struct list_head *next);
  22. #endif
  23. /**
  24. * list_add - add a new entry
  25. * @new: new entry to be added
  26. * @head: list head to add it after
  27. *
  28. * Insert a new entry after the specified head.
  29. * This is good for implementing stacks.
  30. */
  31. #ifndef CONFIG_DEBUG_LIST
  32. static inline void list_add(struct list_head *new, struct list_head *head)
  33. {
  34. __list_add(new, head, head->next);
  35. }
  36. #else
  37. extern void list_add(struct list_head *new, struct list_head *head);
  38. #endif
  39. /**
  40. * list_add_tail - add a new entry
  41. * @new: new entry to be added
  42. * @head: list head to add it before
  43. *
  44. * Insert a new entry before the specified head.
  45. * This is useful for implementing queues.
  46. */
  47. static inline void list_add_tail(struct list_head *new, struct list_head *head)
  48. {
  49. __list_add(new, head->prev, head);
  50. }
  51. `

2.3.2 说明

list_add为头插法,即在链表头部(head 节点)前插入节点。最后打印的时候,先插入的先打印,后插入的后打印。

例如原链表为 1->2->3, 使用list_add插入 4 后变为,4->1->2->3。因为链表时循环的,而且通常没有首尾节点的概念,所以可以把任何一个节点当成 head

同理,list_add_tail为尾插法,即在链表尾部(head 节点)插入节点。最后打印的时候,先插入的后打印,后插入的先打印。

例如原链表为 1->2->3, 使用list_add_tail插入 4 后变为,1->2->3->4。

2.3.3 举例

  1. `#include "mylist.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. struct student
  5. {
  6. struct list_head stu_list;
  7. int ID;
  8. int math;
  9. };
  10. int main()
  11. {
  12. struct student *p;
  13. struct student *q;
  14. struct student stu1;
  15. struct student stu2;
  16. struct list_head *pos;
  17. //链表的初始化
  18. INIT_LIST_HEAD(&stu1.stu_list);
  19. INIT_LIST_HEAD(&stu2.stu_list);
  20. //头插法创建stu stu1链表
  21. for (int i = 0;i < 6;i++) {
  22. p = (struct student *)malloc(sizeof(struct student));
  23. p->ID=i;
  24. p->math = i+80;
  25. //头插法
  26. list_add(&p->stu_list,&stu1.stu_list);
  27. //尾插法
  28. //list_add_tail(&p->list,&stu.list);
  29. }
  30. printf("list_add: \r\n");
  31. list_for_each(pos, &stu1.stu_list) {
  32. printf("ID = %d,math = %d\n",((struct student*)pos)->ID,((struct student*)pos)->math);
  33. }
  34. //尾插法创建stu stu1链表
  35. for (int i = 0;i < 6;i++) {
  36. p = (struct student *)malloc(sizeof(struct student));
  37. p->ID=i;
  38. p->math = i+80;
  39. //头插法
  40. //list_add(&p->stu_list,&stu1.stu_list);
  41. //尾插法
  42. list_add_tail(&p->stu_list,&stu2.stu_list);
  43. }
  44. printf("list_add_tail: \r\n");
  45. list_for_each(pos, &stu2.stu_list) {
  46. printf("ID = %d,math = %d\n",((struct student*)pos)->ID,((struct student*)pos)->math);
  47. }
  48. return 0;
  49. }
  50. `

如何移植并使用Linux内核的通用链表(附完整代码实现) - 图5

测试结果

2.4 链表删除节点

2.4.1 内核实现

  1. `//原来内核设置的删除链表后的指向位置
  2. // # define POISON_POINTER_DELTA 0
  3. // #define LIST_POISON1 ((void *) 0x00100100 + POISON_POINTER_DELTA)
  4. // #define LIST_POISON2 ((void *) 0x00200200 + POISON_POINTER_DELTA)
  5. //这里我们设置为NULL 内核中定义NULL 为0
  6. #define NULL ((void *)0)
  7. #define LIST_POISON1 NULL
  8. #define LIST_POISON2 NULL
  9. /*
  10. * Delete a list entry by making the prev/next entries
  11. * point to each other.
  12. *
  13. * This is only for internal list manipulation where we know
  14. * the prev/next entries already!
  15. */
  16. static inline void __list_del(struct list_head * prev, struct list_head * next)
  17. {
  18. next->prev = prev;
  19. prev->next = next;
  20. }
  21. /**
  22. * list_del - deletes entry from list.
  23. * @entry: the element to delete from the list.
  24. * Note: list_empty() on entry does not return true after this, the entry is
  25. * in an undefined state.
  26. */
  27. #ifndef CONFIG_DEBUG_LIST
  28. static inline void list_del(struct list_head *entry)
  29. {
  30. __list_del(entry->prev, entry->next);
  31. entry->next = LIST_POISON1;
  32. entry->prev = LIST_POISON2;
  33. }
  34. #else
  35. extern void list_del(struct list_head *entry);
  36. #endif
  37. `

2.4.2 说明

链表删除之后,entry 的前驱和后继会分别指向LIST_POISON1LIST_POISON2,这个是内核设置的一个区域,但是在本例中将其置为了NULL

2.4.3 举例

  1. `#include "mylist.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. struct student
  5. {
  6. struct list_head stu_list;
  7. int ID;
  8. int math;
  9. };
  10. int main()
  11. {
  12. struct student *p;
  13. struct student *q;
  14. struct student stu1;
  15. struct student stu2;
  16. struct list_head *pos1;
  17. //注意这里的pos2,后面会解释为什么定义为
  18. struct student *pos2;
  19. //stu = (struct student*)malloc(sizeof(struct student));
  20. //链表的初始化
  21. INIT_LIST_HEAD(&stu1.stu_list);
  22. INIT_LIST_HEAD(&stu2.stu_list);
  23. LIST_HEAD(stu);
  24. //头插法创建stu stu1链表
  25. for (int i = 0;i < 6;i++) {
  26. p = (struct student *)malloc(sizeof(struct student));
  27. p->ID=i;
  28. p->math = i+80;
  29. //头插法
  30. list_add(&p->stu_list,&stu1.stu_list);
  31. //尾插法
  32. //list_add_tail(&p->list,&stu.list);
  33. }
  34. printf("list_add: \r\n");
  35. list_for_each(pos1, &stu1.stu_list) {
  36. printf("ID = %d,math = %d\n",((struct student*)pos1)->ID,((struct student*)pos1)->math);
  37. }
  38. //删除
  39. list_for_each_entry(pos2,&stu1.stu_list,stu_list) {
  40. if (pos2->ID == 4) {
  41. list_del(&pos2->stu_list);
  42. break;
  43. }
  44. }
  45. printf("list_del\r\n");
  46. list_for_each_entry(pos2,&stu1.stu_list,stu_list) {
  47. printf("ID = %d,math = %d\n",pos2->ID,pos2->math);
  48. }
  49. return 0;
  50. }
  51. `

如何移植并使用Linux内核的通用链表(附完整代码实现) - 图6

测试结果

2.5 链表替换节点

2.5.1 内核实现

  1. `/**
  2. * list_replace - replace old entry by new one
  3. * @old : the element to be replaced
  4. * @new : the new element to insert
  5. *
  6. * If @old was empty, it will be overwritten.
  7. */
  8. static inline void list_replace(struct list_head *old,
  9. struct list_head *new)
  10. {
  11. new->next = old->next;
  12. new->next->prev = new;
  13. new->prev = old->prev;
  14. new->prev->next = new;
  15. }
  16. static inline void list_replace_init(struct list_head *old,
  17. struct list_head *new)
  18. {
  19. list_replace(old, new);
  20. INIT_LIST_HEAD(old);//重新初始化
  21. }
  22. `

2.5.2 说明

list_replace使用新的节点替换旧的节点。

list_replace_initlist_replace不同之处在于,list_replace_init会将旧的节点重新初始化,让前驱和后继指向自己。

2.5.3 举例

  1. `#include "mylist.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. struct student
  5. {
  6. struct list_head stu_list;
  7. int ID;
  8. int math;
  9. };
  10. int main()
  11. {
  12. struct student *p;
  13. struct student *q;
  14. struct student stu1;
  15. struct student stu2;
  16. struct list_head *pos1;
  17. struct student *pos2;
  18. struct student new_obj={.ID=100,.math=100};
  19. //stu = (struct student*)malloc(sizeof(struct student));
  20. //链表的初始化
  21. INIT_LIST_HEAD(&stu1.stu_list);
  22. INIT_LIST_HEAD(&stu2.stu_list);
  23. LIST_HEAD(stu);
  24. //头插法创建stu stu1链表
  25. for (int i = 0;i < 6;i++) {
  26. p = (struct student *)malloc(sizeof(struct student));
  27. p->ID=i;
  28. p->math = i+80;
  29. //头插法
  30. list_add(&p->stu_list,&stu1.stu_list);
  31. //尾插法
  32. //list_add_tail(&p->list,&stu.list);
  33. }
  34. printf("list_add: \r\n");
  35. list_for_each(pos1, &stu1.stu_list) {
  36. printf("ID = %d,math = %d\n",((struct student*)pos1)->ID,((struct student*)pos1)->math);
  37. }
  38. //替换
  39. list_for_each_entry(pos2,&stu1.stu_list,stu_list) {
  40. if (pos2->ID == 4) {
  41. list_replace(&pos2->stu_list,&new_obj.stu_list);
  42. break;
  43. }
  44. }
  45. printf("list_replace\r\n");
  46. list_for_each_entry(pos2,&stu1.stu_list,stu_list) {
  47. printf("ID = %d,math = %d\n",pos2->ID,pos2->math);
  48. }
  49. return 0;
  50. }
  51. `

如何移植并使用Linux内核的通用链表(附完整代码实现) - 图7

测试结果

2.6 链表删除并插入节点

2.6.1 内核实现

  1. `/**
  2. * list_move - delete from one list and add as another's head
  3. * @list: the entry to move
  4. * @head: the head that will precede our entry
  5. */
  6. static inline void list_move(struct list_head *list, struct list_head *head)
  7. {
  8. __list_del(list->prev, list->next);
  9. list_add(list, head);
  10. }
  11. /**
  12. * list_move_tail - delete from one list and add as another's tail
  13. * @list: the entry to move
  14. * @head: the head that will follow our entry
  15. */
  16. static inline void list_move_tail(struct list_head *list,
  17. struct list_head *head)
  18. {
  19. __list_del(list->prev, list->next);
  20. list_add_tail(list, head);
  21. }
  22. `

2.6.2 说明

list_move函数实现的功能是删除 list 指向的节点,同时将其以头插法插入到 head 中list_move_taillist_move功能类似,只不过是将 list 节点插入到了head 的尾部

2.6.3 举例

  1. `#include "mylist.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. struct student
  5. {
  6. struct list_head stu_list;
  7. int ID;
  8. int math;
  9. };
  10. int main()
  11. {
  12. struct student *p;
  13. struct student *q;
  14. struct student stu1;
  15. struct student stu2;
  16. struct list_head *pos1;
  17. struct student *pos2;
  18. struct student new_obj={.ID=100,.math=100};
  19. //stu = (struct student*)malloc(sizeof(struct student));
  20. //链表的初始化
  21. INIT_LIST_HEAD(&stu1.stu_list);
  22. INIT_LIST_HEAD(&stu2.stu_list);
  23. LIST_HEAD(stu);
  24. //头插法创建stu stu1链表
  25. for (int i = 0;i < 6;i++) {
  26. p = (struct student *)malloc(sizeof(struct student));
  27. p->ID=i;
  28. p->math = i+80;
  29. //头插法
  30. list_add(&p->stu_list,&stu1.stu_list);
  31. //尾插法
  32. //list_add_tail(&p->list,&stu.list);
  33. }
  34. printf("list_add: \r\n");
  35. list_for_each(pos1, &stu1.stu_list) {
  36. printf("ID = %d,math = %d\n",((struct student*)pos1)->ID,((struct student*)pos1)->math);
  37. }
  38. //移位替换
  39. list_for_each_entry(pos2,&stu1.stu_list,stu_list) {
  40. if (pos2->ID == 0) {
  41. list_move(&pos2->stu_list,&stu1.stu_list);
  42. break;
  43. }
  44. }
  45. printf("list_move\r\n");
  46. list_for_each_entry(pos2,&stu1.stu_list,stu_list) {
  47. printf("ID = %d,math = %d\n",pos2->ID,pos2->math);
  48. }
  49. return 0;
  50. }
  51. `

如何移植并使用Linux内核的通用链表(附完整代码实现) - 图8

测试结果

2.7 链表的合并

2.7.1 内核实现

  1. `static inline void __list_splice(struct list_head *list,
  2. struct list_head *head)
  3. {
  4. struct list_head *first = list->next;
  5. struct list_head *last = list->prev;
  6. struct list_head *at = head->next;
  7. first->prev = head;
  8. head->next = first;
  9. last->next = at;
  10. at->prev = last;
  11. }
  12. /**
  13. * list_splice - join two lists
  14. * @list: the new list to add.
  15. * @head: the place to add it in the first list.
  16. */
  17. static inline void list_splice(struct list_head *list, struct list_head *head)
  18. {
  19. if (!list_empty(list))
  20. __list_splice(list, head);
  21. }
  22. /**
  23. * list_splice_init - join two lists and reinitialise the emptied list.
  24. * @list: the new list to add.
  25. * @head: the place to add it in the first list.
  26. *
  27. * The list at @list is reinitialised
  28. */
  29. static inline void list_splice_init(struct list_head *list,
  30. struct list_head *head)
  31. {
  32. if (!list_empty(list)) {
  33. __list_splice(list, head);
  34. INIT_LIST_HEAD(list);//置空
  35. }
  36. }
  37. `

2.7.2 说明

list_splice完成的功能是合并两个链表。

假设当前有两个链表,表头分别是stu_list1stu_list2(都是struct list_head变量),当调用list_splice(&stu_list1,&stu_list2)时,只要stu_list1非空,stu_list1链表的内容将被挂接在stu_list2链表上,位于stu_list2stu_list2.next(原stu_list2表的第一个节点)之间。新stu_list2链表将以原stu_list1表的第一个节点为首节点,而尾节点不变。

如何移植并使用Linux内核的通用链表(附完整代码实现) - 图9

合并两个链表

list_splice_initlist_splice类似,只不过在合并完之后,调用INIT_LIST_HEAD(list)将 list 设置为空链。

2.7.3 用例

  1. `#include "mylist.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. struct student
  5. {
  6. struct list_head stu_list;
  7. int ID;
  8. int math;
  9. };
  10. int main()
  11. {
  12. struct student *p;
  13. struct student *q;
  14. struct student stu1;
  15. struct student stu2;
  16. struct list_head *pos1;
  17. struct student *pos2;
  18. struct student new_obj={.ID=100,.math=100};
  19. //stu = (struct student*)malloc(sizeof(struct student));
  20. //链表的初始化
  21. INIT_LIST_HEAD(&stu1.stu_list);
  22. INIT_LIST_HEAD(&stu2.stu_list);
  23. LIST_HEAD(stu);
  24. //头插法创建stu1 list链表
  25. for (int i = 0;i < 6;i++) {
  26. p = (struct student *)malloc(sizeof(struct student));
  27. p->ID=i;
  28. p->math = i+80;
  29. //头插法
  30. list_add(&p->stu_list,&stu1.stu_list);
  31. //尾插法
  32. //list_add_tail(&p->list,&stu.list);
  33. }
  34. printf("stu1: \r\n");
  35. list_for_each(pos1, &stu1.stu_list) {
  36. printf("ID = %d,math = %d\n",((struct student*)pos1)->ID,((struct student*)pos1)->math);
  37. }
  38. //头插法创建stu2 list 链表
  39. for (int i = 0;i < 3;i++) {
  40. q = (struct student *)malloc(sizeof(struct student));
  41. q->ID=i;
  42. q->math = i+80;
  43. //头插法
  44. list_add(&q->stu_list,&stu2.stu_list);
  45. //尾插法
  46. //list_add_tail(&p->list,&stu.list);
  47. }
  48. printf("stu2: \r\n");
  49. list_for_each(pos1, &stu2.stu_list) {
  50. printf("ID = %d,math = %d\n",((struct student*)pos1)->ID,((struct student*)pos1)->math);
  51. }
  52. //合并
  53. list_splice(&stu1.stu_list,&stu2.stu_list);
  54. printf("list_splice\r\n");
  55. list_for_each(pos1, &stu2.stu_list) {
  56. printf("stu2 ID = %d,math = %d\n",((struct student*)pos1)->ID,((struct student*)pos1)->math);
  57. }
  58. return 0;
  59. }
  60. `

如何移植并使用Linux内核的通用链表(附完整代码实现) - 图10

测试结果

2.8 链表的遍历

2.8.1 内核实现

  1. `//计算member在type中的位置
  2. #define offsetof(type, member) (size_t)(&((type*)0)->member)
  3. //根据member的地址获取type的起始地址
  4. #define container_of(ptr, type, member) ({ \
  5. const typeof(((type *)0)->member)*__mptr = (ptr); \
  6. (type *)((char *)__mptr - offsetof(type, member)); })
  7. /**
  8. * list_entry - get the struct for this entry
  9. * @ptr: the &struct list_head pointer.
  10. * @type: the type of the struct this is embedded in.
  11. * @member: the name of the list_struct within the struct.
  12. */
  13. #define list_entry(ptr, type, member) \
  14. container_of(ptr, type, member)
  15. /**
  16. * list_first_entry - get the first element from a list
  17. * @ptr: the list head to take the element from.
  18. * @type: the type of the struct this is embedded in.
  19. * @member: the name of the list_struct within the struct.
  20. *
  21. * Note, that list is expected to be not empty.
  22. */
  23. #define list_first_entry(ptr, type, member) \
  24. list_entry((ptr)->next, type, member)
  25. /**
  26. * list_for_each - iterate over a list
  27. * @pos: the &struct list_head to use as a loop cursor.
  28. * @head: the head for your list.
  29. */
  30. #define list_for_each(pos, head) \
  31. for (pos = (head)->next; prefetch(pos->next), pos != (head); \
  32. pos = pos->next)
  33. /**
  34. * __list_for_each - iterate over a list
  35. * @pos: the &struct list_head to use as a loop cursor.
  36. * @head: the head for your list.
  37. *
  38. * This variant differs from list_for_each() in that it's the
  39. * simplest possible list iteration code, no prefetching is done.
  40. * Use this for code that knows the list to be very short (empty
  41. * or 1 entry) most of the time.
  42. */
  43. #define __list_for_each(pos, head) \
  44. for (pos = (head)->next; pos != (head); pos = pos->next)
  45. /**
  46. * list_for_each_prev - iterate over a list backwards
  47. * @pos: the &struct list_head to use as a loop cursor.
  48. * @head: the head for your list.
  49. */
  50. #define list_for_each_prev(pos, head) \
  51. for (pos = (head)->prev; prefetch(pos->prev), pos != (head); \
  52. pos = pos->prev)
  53. /**
  54. * list_for_each_safe - iterate over a list safe against removal of list entry
  55. * @pos: the &struct list_head to use as a loop cursor.
  56. * @n: another &struct list_head to use as temporary storage
  57. * @head: the head for your list.
  58. */
  59. #define list_for_each_safe(pos, n, head) \
  60. for (pos = (head)->next, n = pos->next; pos != (head); \
  61. pos = n, n = pos->next)
  62. /**
  63. * list_for_each_entry - iterate over list of given type
  64. * @pos: the type * to use as a loop cursor.
  65. * @head: the head for your list.
  66. * @member: the name of the list_struct within the struct.
  67. */
  68. #define list_for_each_entry(pos, head, member) \
  69. for (pos = list_entry((head)->next, typeof(*pos), member); \
  70. prefetch(pos->member.next), &pos->member != (head); \
  71. pos = list_entry(pos->member.next, typeof(*pos), member))
  72. /**
  73. * list_for_each_entry_reverse - iterate backwards over list of given type.
  74. * @pos: the type * to use as a loop cursor.
  75. * @head: the head for your list.
  76. * @member: the name of the list_struct within the struct.
  77. */
  78. #define list_for_each_entry_reverse(pos, head, member) \
  79. for (pos = list_entry((head)->prev, typeof(*pos), member); \
  80. prefetch(pos->member.prev), &pos->member != (head); \
  81. pos = list_entry(pos->member.prev, typeof(*pos), member))
  82. /**
  83. * list_prepare_entry - prepare a pos entry for use in list_for_each_entry_continue()
  84. * @pos: the type * to use as a start point
  85. * @head: the head of the list
  86. * @member: the name of the list_struct within the struct.
  87. *
  88. * Prepares a pos entry for use as a start point in list_for_each_entry_continue().
  89. */
  90. #define list_prepare_entry(pos, head, member) \
  91. ((pos) ? : list_entry(head, typeof(*pos), member))
  92. /**
  93. * list_for_each_entry_continue - continue iteration over list of given type
  94. * @pos: the type * to use as a loop cursor.
  95. * @head: the head for your list.
  96. * @member: the name of the list_struct within the struct.
  97. *
  98. * Continue to iterate over list of given type, continuing after
  99. * the current position.
  100. */
  101. #define list_for_each_entry_continue(pos, head, member) \
  102. for (pos = list_entry(pos->member.next, typeof(*pos), member); \
  103. prefetch(pos->member.next), &pos->member != (head); \
  104. pos = list_entry(pos->member.next, typeof(*pos), member))
  105. /**
  106. * list_for_each_entry_from - iterate over list of given type from the current point
  107. * @pos: the type * to use as a loop cursor.
  108. * @head: the head for your list.
  109. * @member: the name of the list_struct within the struct.
  110. *
  111. * Iterate over list of given type, continuing from current position.
  112. */
  113. #define list_for_each_entry_from(pos, head, member) \
  114. for (; prefetch(pos->member.next), &pos->member != (head); \
  115. pos = list_entry(pos->member.next, typeof(*pos), member))
  116. /**
  117. * list_for_each_entry_safe - iterate over list of given type safe against removal of list entry
  118. * @pos: the type * to use as a loop cursor.
  119. * @n: another type * to use as temporary storage
  120. * @head: the head for your list.
  121. * @member: the name of the list_struct within the struct.
  122. */
  123. #define list_for_each_entry_safe(pos, n, head, member) \
  124. for (pos = list_entry((head)->next, typeof(*pos), member), \
  125. n = list_entry(pos->member.next, typeof(*pos), member); \
  126. &pos->member != (head); \
  127. pos = n, n = list_entry(n->member.next, typeof(*n), member))
  128. /**
  129. * list_for_each_entry_safe_continue
  130. * @pos: the type * to use as a loop cursor.
  131. * @n: another type * to use as temporary storage
  132. * @head: the head for your list.
  133. * @member: the name of the list_struct within the struct.
  134. *
  135. * Iterate over list of given type, continuing after current point,
  136. * safe against removal of list entry.
  137. */
  138. #define list_for_each_entry_safe_continue(pos, n, head, member) \
  139. for (pos = list_entry(pos->member.next, typeof(*pos), member), \
  140. n = list_entry(pos->member.next, typeof(*pos), member); \
  141. &pos->member != (head); \
  142. pos = n, n = list_entry(n->member.next, typeof(*n), member))
  143. /**
  144. * list_for_each_entry_safe_from
  145. * @pos: the type * to use as a loop cursor.
  146. * @n: another type * to use as temporary storage
  147. * @head: the head for your list.
  148. * @member: the name of the list_struct within the struct.
  149. *
  150. * Iterate over list of given type from current point, safe against
  151. * removal of list entry.
  152. */
  153. #define list_for_each_entry_safe_from(pos, n, head, member) \
  154. for (n = list_entry(pos->member.next, typeof(*pos), member); \
  155. &pos->member != (head); \
  156. pos = n, n = list_entry(n->member.next, typeof(*n), member))
  157. /**
  158. * list_for_each_entry_safe_reverse
  159. * @pos: the type * to use as a loop cursor.
  160. * @n: another type * to use as temporary storage
  161. * @head: the head for your list.
  162. * @member: the name of the list_struct within the struct.
  163. *
  164. * Iterate backwards over list of given type, safe against removal
  165. * of list entry.
  166. */
  167. #define list_for_each_entry_safe_reverse(pos, n, head, member) \
  168. for (pos = list_entry((head)->prev, typeof(*pos), member), \
  169. n = list_entry(pos->member.prev, typeof(*pos), member); \
  170. &pos->member != (head); \
  171. pos = n, n = list_entry(n->member.prev, typeof(*n), member))
  172. `

2.8.2 说明

list_entry(ptr, type, member)可以得到节点结构体的地址,得到地址后就可以对结构体中的元素进行操作了。依靠list_entry(ptr, type, member)函数,内核链表的增删查改都不需要知道list_head结构体所嵌入式的对象,就可以完成各种操作。

为什么这里使用container_of来定义list_entry(ptr, type, member)结构体呢,下面会详细解释

list_first_entry(ptr, type, member)得到的是结构体中第一个元素的地址

list_for_each(pos, head)是用来正向遍历链表的,pos 相当于一个临时的节点,用来不断指向下一个节点。

list_for_each_prev(pos, head)list_for_each_entry_reverse(pos, head, member)是用来倒着遍历链表的。

list_for_each_safe(pos, n, head)list_for_each_entry_safe(pos, n, head, member),这两个函数是为了避免在遍历链表的过程中因 pos 节点被释放而造成的断链。这个时候就要求我们另外提供一个与 pos 同类型的指针 n,在 for 循环中暂存 pos 下一个节点的地址。(内核的设计者考虑的真是全面!)

list_prepare_entry(pos, head, member)用于准备一个结构体的首地址,用在list_for_each_entry_contine()中。

list_for_each_entry_continue(pos, head, member)从当前 pos 的下一个节点开始继续遍历剩余的链表,不包括 pos. 如果我们将 pos、head、member 传入list_for_each_entry,此宏将会从链表的头节点开始遍历。

list_for_each_entry_continue_reverse(pos, head, member)从当前的 pos 的前一个节点开始继续反向遍历剩余的链表,不包括 pos。

list_for_each_entry_from(pos, head, member)从 pos 开始遍历剩余的链表。

list_for_each_entry_safe_continue(pos, n, head, member)从 pos 节点的下一个节点开始遍历剩余的链表,并防止因删除链表节点而导致的遍历出错。

list_for_each_entry_safe_from(pos, n, head, member)从 pos 节点开始继续遍历剩余的链表,并防止因删除链表节点而导致的遍历出错。其与list_for_each_entry_safe_continue(pos, n, head, member)的不同在于在第一次遍历时,pos 没有指向它的下一个节点,而是从 pos 开始遍历。

list_for_each_entry_safe_reverse(pos, n, head, member)从 pos 的前一个节点开始反向遍历一个链表,并防止因删除链表节点而导致的遍历出错。

list_safe_reset_next(pos, n, member)返回当前 pos 节点的下一个节点的 type 结构体首地址。

2.8.3 举例

  1. `#include "mylist.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. struct student
  5. {
  6. struct list_head stu_list;
  7. int ID;
  8. int math;
  9. };
  10. int main()
  11. {
  12. struct student *p;
  13. struct student *q;
  14. struct student stu1;
  15. struct student stu2;
  16. struct list_head *pos1;
  17. struct student *pos2;
  18. struct student new_obj={.ID=100,.math=100};
  19. //stu = (struct student*)malloc(sizeof(struct student));
  20. //链表的初始化
  21. INIT_LIST_HEAD(&stu1.stu_list);
  22. INIT_LIST_HEAD(&stu2.stu_list);
  23. LIST_HEAD(stu);
  24. //头插法创建stu stu1链表
  25. for (int i = 0;i < 6;i++) {
  26. p = (struct student *)malloc(sizeof(struct student));
  27. p->ID=i;
  28. p->math = i+80;
  29. //头插法
  30. list_add(&p->stu_list,&stu1.stu_list);
  31. //尾插法
  32. //list_add_tail(&p->list,&stu.list);
  33. }
  34. printf("stu1: \r\n");
  35. list_for_each(pos1, &stu1.stu_list) {
  36. printf("ID = %d,math = %d\n",((struct student*)pos1)->ID,((struct student*)pos1)->math);
  37. }
  38. printf("list_for_each_prev\r\n");
  39. list_for_each_prev(pos1, &stu1.stu_list){
  40. printf("stu2 ID = %d,math = %d\n",((struct student*)pos1)->ID,((struct student*)pos1)->math);
  41. }
  42. return 0;
  43. }
  44. `

如何移植并使用Linux内核的通用链表(附完整代码实现) - 图11

测试结果

例子就不都写出来了,感兴趣的可以自己试试。

3. 疑惑解答

之前我们定义结构体的时候是把 struct list_head放在首位的,当使用list_for_each遍历的时候,pos 获取的位置就是结构体的位置,也就是链表的位置。如下所示。

  1. ` struct student
  2. {
  3. struct list_head list;//暂且将链表放在结构体的第一位
  4. int ID;
  5. int math;
  6. };
  7. `
  1. ` list_for_each(pos, &stu1.stu_list) {
  2. printf("ID = %d,math = %d\n",((struct student*)pos)->ID,((struct student*)pos)->math);
  3. }
  4. `

但是当我们把struct list_head list;放在最后时,pos 获取的显然就已经不是链表的位置了,那么当我们再次调用list_for_each时就会出错。

  1. struct student
  2. {
  3. int ID;
  4. int math;
  5. struct list_head list;//暂且将链表放在结构体的第一位
  6. };

list_for_each_entry这个函数表示在遍历的时候获取 entry,该宏中的 pos 类型为容器结构类型的指针,这与前面list_for_each中的使用的类型不再相同(这也就是为什么我们上面会分别定义 pos1 和 pos2 的原因了)。

不过这也是情理之中的事,毕竟现在的 pos,我要使用该指针去访问数据域的成员 age 了;head 是你使用INIT_LIST_HEAD初始化的那个对象,即头指针,注意,不是头结点;member 就是容器结构中的链表元素对象。使用该宏替代前面的方法。这个时候就要用到container_of这个宏了。(再一次感叹内核设计者的伟大)。

关于container_of宏将在下一篇文章详细介绍,这里先知道如何使用就可以。

4. list.h 移植源码

这里需要注意一点,如果是在 GNU 中使用 GCC 进行程序开发,可以不做更改,直接使用上面的函数即可;但如果你想把其移植到 Windows 环境中进行使用,可以直接将 prefetch 语句删除即可,因为 prefetch 函数它通过对数据手工预取的方法,减少了读取延迟,从而提高了性能,也就是prefetch 是 GCC 用来提高效率的函数,如果要移植到非 GNU 环境,可以换成相应环境的预取函数或者直接删除也可,它并不影响链表的功能。

  1. #ifndef _MYLIST_H
  2. #define _MYLIST_H
  3. //原来链表删除后指向的位置,这里我们修改成 0
  4. // # define POISON_POINTER_DELTA 0
  5. // #define LIST_POISON1 ((void *) 0x00100100 + POISON_POINTER_DELTA)
  6. // #define LIST_POISON2 ((void *) 0x00200200 + POISON_POINTER_DELTA)
  7. #define NULL ((void *)0)
  8. #define LIST_POISON1 NULL
  9. #define LIST_POISON2 NULL
  10. //计算member在type中的位置
  11. #define offsetof(type, member) (size_t)(&((type*)0)->member)
  12. //根据member的地址获取type的起始地址
  13. #define container_of(ptr, type, member) ({ \
  14. const typeof(((type *)0)->member)*__mptr = (ptr); \
  15. (type *)((char *)__mptr - offsetof(type, member)); })
  16. //链表结构
  17. struct list_head
  18. {
  19. struct list_head *prev;
  20. struct list_head *next;
  21. };
  22. #define LIST_HEAD_INIT(name) { &(name), &(name) }
  23. #define LIST_HEAD(name) \
  24. struct list_head name = LIST_HEAD_INIT(name)
  25. static inline void INIT_LIST_HEAD(struct list_head *list)
  26. {
  27. list->next = list;
  28. list->prev = list;
  29. }
  30. static inline void init_list_head(struct list_head *list)
  31. {
  32. list->prev = list;
  33. list->next = list;
  34. }
  35. #ifndef CONFIG_DEBUG_LIST
  36. static inline void __list_add(struct list_head *new,
  37. struct list_head *prev,
  38. struct list_head *next)
  39. {
  40. next->prev = new;
  41. new->next = next;
  42. new->prev = prev;
  43. prev->next = new;
  44. }
  45. #else
  46. extern void __list_add(struct list_head *new,
  47. struct list_head *prev,
  48. struct list_head *next);
  49. #endif
  50. //从头部添加
  51. /**
  52. * list_add - add a new entry
  53. * @new: new entry to be added
  54. * @head: list head to add it after
  55. *
  56. * Insert a new entry after the specified head.
  57. * This is good for implementing stacks.
  58. */
  59. #ifndef CONFIG_DEBUG_LIST
  60. static inline void list_add(struct list_head *new, struct list_head *head)
  61. {
  62. __list_add(new, head, head->next);
  63. }
  64. #else
  65. extern void list_add(struct list_head *new, struct list_head *head);
  66. #endif
  67. //从尾部添加
  68. static inline void list_add_tail(struct list_head *new, struct list_head *head)
  69. {
  70. __list_add(new, head->prev, head);
  71. }
  72. static inline void __list_del(struct list_head *prev, struct list_head *next)
  73. {
  74. prev->next = next;
  75. next->prev = prev;
  76. }
  77. static inline void list_del(struct list_head *entry)
  78. {
  79. __list_del(entry->prev, entry->next);
  80. entry->next = LIST_POISON1;
  81. entry->prev = LIST_POISON2;
  82. }
  83. static inline void __list_splice(struct list_head *list,
  84. struct list_head *head)
  85. {
  86. struct list_head *first = list->next;
  87. struct list_head *last = list->prev;
  88. struct list_head *at = head->next;
  89. first->prev = head;
  90. head->next = first;
  91. last->next = at;
  92. at->prev = last;
  93. }
  94. /**
  95. * list_empty - tests whether a list is empty
  96. * @head: the list to test.
  97. */
  98. static inline int list_empty(const struct list_head *head)
  99. {
  100. return head->next == head;
  101. }
  102. /**
  103. * list_splice - join two lists
  104. * @list: the new list to add.
  105. * @head: the place to add it in the first list.
  106. */
  107. static inline void list_splice(struct list_head *list, struct list_head *head)
  108. {
  109. if (!list_empty(list))
  110. __list_splice(list, head);
  111. }
  112. /**
  113. * list_replace - replace old entry by new one
  114. * @old : the element to be replaced
  115. * @new : the new element to insert
  116. *
  117. * If @old was empty, it will be overwritten.
  118. */
  119. static inline void list_replace(struct list_head *old,
  120. struct list_head *new)
  121. {
  122. new->next = old->next;
  123. new->next->prev = new;
  124. new->prev = old->prev;
  125. new->prev->next = new;
  126. }
  127. static inline void list_replace_init(struct list_head *old,
  128. struct list_head *new)
  129. {
  130. list_replace(old, new);
  131. INIT_LIST_HEAD(old);
  132. }
  133. /**
  134. * list_move - delete from one list and add as another's head
  135. * @list: the entry to move
  136. * @head: the head that will precede our entry
  137. */
  138. static inline void list_move(struct list_head *list, struct list_head *head)
  139. {
  140. __list_del(list->prev, list->next);
  141. list_add(list, head);
  142. }
  143. /**
  144. * list_move_tail - delete from one list and add as another's tail
  145. * @list: the entry to move
  146. * @head: the head that will follow our entry
  147. */
  148. static inline void list_move_tail(struct list_head *list,
  149. struct list_head *head)
  150. {
  151. __list_del(list->prev, list->next);
  152. list_add_tail(list, head);
  153. }
  154. #define list_entry(ptr, type, member) \
  155. container_of(ptr, type, member)
  156. #define list_first_entry(ptr, type, member) \
  157. list_entry((ptr)->next, type, member)
  158. #define list_for_each(pos, head) \
  159. for (pos = (head)->next; pos != (head); pos = pos->next)
  160. /**
  161. * list_for_each_entry - iterate over list of given type
  162. * @pos: the type * to use as a loop cursor.
  163. * @head: the head for your list.
  164. * @member: the name of the list_struct within the struct.
  165. */
  166. #define list_for_each_entry(pos, head, member) \
  167. for (pos = list_entry((head)->next, typeof(*pos), member); \
  168. &pos->member != (head); \
  169. pos = list_entry(pos->member.next, typeof(*pos), member))
  170. /**
  171. * list_for_each_prev - iterate over a list backwards
  172. * @pos: the &struct list_head to use as a loop cursor.
  173. * @head: the head for your list.
  174. */
  175. #define list_for_each_prev(pos, head) \
  176. for (pos = (head)->prev; pos != (head); \
  177. pos = pos->prev)