list_for_each_entry_safe 简介

list_for_each_entry_safe 是 Linux 内核中用于遍历链表的一个宏,特别适用于在遍历过程中可能需要删除链表节点的场景。它的设计保证了在删除当前节点时,不会影响后续节点的访问,从而实现安全的遍历。

定义

c 复制代码
#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))

参数说明

  1. pos: 当前遍历到的链表节点对应的结构体指针。
  2. n: 临时指针,用于保存下一个节点的位置。
  3. head: 链表头节点的地址。
  4. member: 链表节点在结构体中的成员名。

工作原理

  • list_for_each_entry_safe 在每次循环中,使用 n 保存当前节点的下一个节点地址。
  • 即使在循环中删除了当前节点(由 pos 指向),由于 n 已经保存了下一个节点的位置,后续遍历可以继续进行而不受影响。

使用场景

主要用于需要在遍历链表的同时删除链表节点的场景。例如:

示例代码:遍历并删除链表节点

c 复制代码
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

c 复制代码
struct my_list *pos;

// 遍历链表
list_for_each_entry(pos, &head, list) {
    printk(KERN_INFO "Data: %d\n", pos->data);
}

list_for_each_entry 的区别

  • list_for_each_entry: 用于普通遍历,不支持安全删除操作。
  • list_for_each_entry_safe: 在遍历过程中允许安全地删除当前节点。

总结

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

相关推荐
尤物程序猿39 分钟前
【2025面试Java常问八股之redis】zset数据结构的实现,跳表和B+树的对比
数据结构·redis·面试
SsummerC2 小时前
【leetcode100】零钱兑换Ⅱ
数据结构·python·算法·leetcode·动态规划
好易学·数据结构3 小时前
可视化图解算法:二叉树的最大深度(高度)
数据结构·算法·二叉树·最大高度·最大深度·二叉树高度·二叉树深度
小鹿鹿啊3 小时前
C语言编程--15.四数之和
c语言·数据结构·算法
rigidwill6664 小时前
LeetCode hot 100—最长有效括号
数据结构·c++·算法·leetcode·职场和发展
T.Ree.4 小时前
【数据结构】_树和二叉树
c语言·开发语言·数据结构
菜鸟射手4 小时前
QT creater和vs2017文件路径问题
linux·c++·windows·qt
爱编程的鱼5 小时前
Windows 各版本查找计算机 IP 地址指南
人工智能·windows·网络协议·tcp/ip·tensorflow
sukalot5 小时前
Windows 图形显示驱动开发-WDDM 1.2功能—Windows 8 中的 DirectX 功能改进(九)
windows
simple_whu5 小时前
解决编译pcl时报错‘chrono_literals‘: is not a member of ‘std‘
c++·windows·visual studio