list_for_each与list_for_each_entry详解
2014-05-12 11:22
471 查看
一、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,¤t->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:
___________ ____________
| |
| |
| |
| |
| ........... | | ................
|
| |
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,¤t->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:
___________ ____________
| |
| |
| |
| |
| ........... | | ................
|
| |
相关文章推荐
- 10 篇对初学者和专家都有用的 Linux 命令教程
- Linux 与 Windows 对UNICODE 的处理方式
- Ubuntu12.04下QQ完美走起啊!走起啊!有木有啊!
- 解決Linux下Android开发真机调试设备不被识别问题
- 运维入门
- 运维提升
- Linux 自检和 SystemTap
- Ubuntu Linux使用体验
- c语言实现hashmap(转载)
- Linux 信号signal处理机制
- linux下mysql添加用户
- Scientific Linux 5.5 图形安装教程
- 基于 Linux 集群环境上 GPFS 的问题诊断
- 谁是桌面王者?Win PK Linux三大镇山之宝
- vivi下重新调整分区
- Linux VS Unix:Linux欲一统天下 Unix不死
- linux下设定环境变量
- Linux下修改MySQL编码的方法
- Linux串口通信