list_for_each与list_for_each_entry具体解释

一、list_for_each

1.list_for_each原型
#define list_for_each(pos, head) \
    for (pos = (head)->next, prefetch(pos->next); pos != (head); \
    pos = pos->next, prefetch(pos->next))
它实际上是一个 for 循环。利用传入的pos 作为循环变量,从表头 head開始,逐项向后(next方向)移动 pos ,直至又回到 head (prefetch() 能够不考虑。用于预取以提高遍历速度)。
注意:此宏必要把list_head放在数据结构第一项成员,至此。它的地址也就是结构变量的地址。

2.用法(以訪问当前进程的子进程为例):

struct list_head {
 struct list_head *next, *prev;
};

在struct task_struct 中有例如以下定义:
struct list_head children;

所以

struct task_struct *task;

struct list_head *list;

list_for_each(list,&current->chilidren) {

              task = list_entry(list, struct task_struct, sibling);/*task指向当前的某个子进程*/

}

当中用到了函数list_entry():
这个函数的作用在图1中表示就是能够通过已知的指向member子项的指针,获得整个结构体的指针(地址)
#define list_entry(ptr, type, member) \
        container_of(ptr, type, member)

二、list_for_each_entry:
在Linux内核源代码中,常常要对链表进行操作。当中一个非常重要的宏是list_for_each_entry:
意思大体例如以下:
如果仅仅有两个结点,则第一个member代表head,
list_for_each_entry的作用就是循环遍历每个pos中的member子项。
图1:
pos:                                                           pos:
___________                                        ____________
|                       |                                     |                          |
|                       |                                     |                          |
|    ...........        |                                     |   ................       |
|                       |                        

posted on 2019-04-04 20:54  xfgnongmin  阅读(2058)  评论(0编辑  收藏  举报

导航