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 内核中处理双向链表的一种高级工具,适合需要在遍历过程中修改或删除链表元素的场景。它通过额外的临时指针确保操作安全,不会破坏链表结构123.

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

相关推荐
csdn_aspnet18 分钟前
Redis 入门:Windows、Mac安装指南
数据库·windows·redis·缓存·mac
十二15 小时前
【洛谷题解】P1083 [NOIP 2012 提高组] 借教室(二分答案 + 差分)
数据结构·c++·算法·蓝桥杯
D e re k ZH17 小时前
C++ 从零入门(一):基础语法与程序结构
数据结构·c++·算法
没差c21 小时前
winsw将jar、nginx等注册为Windows服务
windows·nginx·jar
光谱SpectrAI1 天前
Claude Code 2.1.318 的隐私模块:4 条命令,拦了 2 条
windows
careathers1 天前
【数据结构】基于比较的排序算法 - 交换排序
数据结构·算法·排序算法
H.莓飛1 天前
【C++】【STL】vector_OJ题
linux·服务器·开发语言·数据结构·c++·visual studio
Hello_Pyhx1 天前
NWinfo 导出 Windows 硬件信息:从 JSON 报告到缺项排查
windows·json
老师我太想进步了20262 天前
【数据结构-4】算法美学之顺序表
数据结构·算法
百事牛科技2 天前
Excel的三种密码:防看、防存、防乱改,各管各的
windows·excel