【linux内核中的双向链表-02】list_for_each_safe

在前面的文章《linux内核中的双向链表-01》中描述了双向链表的定义以及常用API,其中有个非常重要的宏定义:list_entry(ptr, type, member)。它可以在已知结构体成员地址的情况下,还原出结构体的首地址。

input子系统的事件处理层对应的内核对象为:struct input_handler,input_handler的node成员串在一起,组成了双向链表,表头节点为:input_handler_list。如下图所示:

思考一个问题:在已知input_handler_list的情况下,如何打印出所有input_handler对象的name成员?

方法一

第一步,遍历以input_handler_list为头节点的双向链表,则每一个节点都是struct list_head node结构,我们定义一个变量pos来接收。遍历双向链表可以使用内核API:list_for_each_safe()。则:

c 复制代码
struct list_head *pos;    // 接收遍历到的当前节点
struct list_head *tmp;    // 临时变量
list_for_each_safe(pos, tmp, &input_handler_list);

第二步,根据获取到的struct list_head node成员,求出其所在的input_handler结构体的首地址,并定义一个变量item来接收。通过成员地址求所在结构体首地址的内核API:list_entry()。则:

c 复制代码
struct input_handler *item;
item = list_entry(pos, struct input_handler, node);

第三步,打印各个input_handler对象的name属性:

c 复制代码
pr_info("handler name: %s\n", item->name);

方法二

直接使用内核API:list_for_each_entry(),其等效于先使用list_for_each_safe()获得各个结构体成员,再使用list_entry()获取各个结构体首地址。

c 复制代码
struct input_handler *item;
list_for_each_entry(item, &input_handler_list, node) {
		pr_info("handler name: %s\n", item->name);
}
相关推荐
Java小白笔记28 分钟前
Docker 安装配置完全指南:MacOS 、Windows、Linux环境下的安装、配置与验证
linux·macos·docker
qetfw2 小时前
CentOS 7 搭建 LDAP 目录服务
linux·运维·centos
ALINX技术博客3 小时前
【黑金云课堂】FPGA技术教程Linux开发:系统进阶-PS DMA
linux·fpga开发
IT方大同4 小时前
linux简介
linux·运维·服务器
mounter6254 小时前
从内存隔离到运行时防线:透视 Linux 内核安全强化的博弈与演进
linux·网络·安全·linux kernel·kernel
微道道5 小时前
Linux盒子局域网内使用 .local 域名访问,告别IP变化烦恼
linux·运维·服务器·hermes
Bug退散师6 小时前
多路IO复用[select版TCP服务器与poll版TCP服务器]与常用网络编程函数详解
linux·服务器·c语言·网络·驱动开发·tcp/ip
xiaoye-duck6 小时前
《Linux系统编程》Linux 系统多线程(一):线程概念(从虚拟地址空间与分页机制到优缺点解析)
linux·线程
国服第二切图仔6 小时前
05-构建与特性开关
linux·服务器·ubuntu
FREEDOM_X6 小时前
嵌入式——定时器工作原理
linux·c语言·单片机·嵌入式硬件·ubuntu