list_for_each_entry_safe
是 Linux 内核中用于遍历链表的一个宏,特别适用于在遍历过程中可能需要删除链表节点的场景。它的设计保证了在删除当前节点时,不会影响后续节点的访问,从而实现安全的遍历。
定义
#define list_for_each_entry_safe(pos, n, head, member) \for (pos = list_entry((head)->next, typeof(*pos), member), \n = list_entry(pos->member.next, typeof(*pos), member); \&pos->member != (head); \pos = n, n = list_entry(n->member.next, typeof(*n), member))
参数说明
pos
: 当前遍历到的链表节点对应的结构体指针。n
: 临时指针,用于保存下一个节点的位置。head
: 链表头节点的地址。member
: 链表节点在结构体中的成员名。
工作原理
list_for_each_entry_safe
在每次循环中,使用n
保存当前节点的下一个节点地址。- 即使在循环中删除了当前节点(由
pos
指向),由于n
已经保存了下一个节点的位置,后续遍历可以继续进行而不受影响。
使用场景
主要用于需要在遍历链表的同时删除链表节点的场景。例如:
示例代码:遍历并删除链表节点
struct my_list {int data;struct list_head list;
};struct my_list *pos, *tmp;// 遍历并删除链表中的所有节点
list_for_each_entry_safe(pos, tmp, &head, list) {printk(KERN_INFO "Data: %d\n", pos->data);list_del(&pos->list); // 从链表中删除当前节点kfree(pos); // 释放内存
}
示例代码:只遍历链表
如果只是遍历而不删除,可以使用 list_for_each_entry
:
struct my_list *pos;// 遍历链表
list_for_each_entry(pos, &head, list) {printk(KERN_INFO "Data: %d\n", pos->data);
}
list_for_each_entry__59">与 list_for_each_entry
的区别
总结
list_for_each_entry_safe
是 Linux 内核中处理双向链表的一种高级工具,适合需要在遍历过程中修改或删除链表元素的场景。它通过额外的临时指针确保操作安全,不会破坏链表结构[1][2][3].
Citations:
[1] https://developer.aliyun.com/article/375545
[2] https://blog.csdn.net/Wang20122013/article/details/112307416
[3] http://www.korantli.com.cn/linux/nei-he-lian-biao/
[4] https://www.cnblogs.com/yangguang-it/p/11667772.html
[5] https://blog.csdn.net/weixin_42645653/article/details/126560076
[6] https://www.cnblogs.com/zhoug2020/p/4972923.html
[7] https://www.51cto.com/article/695735.html
[8] https://juejin.cn/post/7091220406312370213