/********************
* 内核中链表的应用
********************/
Linux内核链表list_head机制详解与使用指南
(1)介绍
Linux内核内部广泛运用链表结构来管理各类数据,涵盖设备列表及多种功能模块的数据组织。这些链表主要依托于位于include/linux/list.h头文件中定义的精妙数据结构实现。
链表数据结构的定义形式十分简洁:
struct list_head {
struct list_head *next, *prev;
};
list_head结构体仅包含两个指向自身类型的指针成员prev和next,内核通常利用这种设计构建双循环链表。
与传统双链表模型不同,此处的list_head不包含任何数据域。在Linux内核链表中,并非链表结构内嵌数据,而是数据结构中包含链表节点。例如:
struct my_struct{
struct list_head list;
unsigned long dog;
void *cat;
};
Linux链表没有固定的表头概念,从任意元素开始访问均可。遍历过程只需从某节点出发,沿指针依次访问后续节点,直至重新回到起始节点即完成循环。因此,每个独立节点均可被视为链表头。
(2)链表的初始化
a.静态
若在编译阶段静态创建链表并直接引用,可采用如下方式:
struct my_struct mine={
.lost = LIST_HEAD_INIT(mine.list);
.dog = 0,
.cat = NULL
};
//或
static LIST_HEAD(fox);
/*等于struct list_head fox = LIST_HEAD_INIT(fox); */
b.动态
struct my_struct *p;
p = kmalloc(GFP_KERNEL, sizeof(my_struct));
p->dog = 0;
p->cat = NULL;
INIT_LIST_HEAD(&p->list);
(3)操作链表
内核提供了一系列用于操作链表的函数接口。
需注意!这些函数均以一个或多个list_head结构体指针作为参数。其定义位于
a.增加节点
list_add(struct list_head *new,
struct list_head *head);
//向指定链表的head节点后面插入new节点
b.把节点增加到链表尾
list_add_tail(struct list_head *new,
struct list_head *head);
//向指定链表的head节点前面插入new节点
c.从链表删除一个节点
list_del(struct list_head *entry);
//将entry从链表中移走
d.把节点从一个链表移到另一个链表
list_move(struct list_head *list,
struct list_head *head);
该操作先从原链表中摘除list项,随后将其插入到head节点的后面。
e.list_empty(struct list_head *head);
若链表为空则返回非0值,否则返回0。
f.合并链表
list_splice(struct list_head *list,
struct list_head *head);
//注意!新的链表不包括list节点
(4)遍历链表
链表本身并非重点,关键在于如何访问包含该链表的结构体实体。
a.从链表指针获得包含该链表的结构体的指针
list_entry(struct list_head *ptr,
type_of_struct,
field_name);
- ptr: list_head指针
- type_of_struct: 包含ptr的结构体类型
- field_name: 结构体中链表字段的名字
如:
my_struct *p = (list_head *ptr, my_struct, list);
b.遍历链表
list_for_each(struct list_head *cursor,
struct list_head *list);
//常常和list_entry配套使用
//注意!用list_for_each遍历时,不包括头节点
c.遍历的同时获得大结构体指针
list_for_each_entry(type *cursor,
struct list_head *list,
member);
d.遍历链表的同时释放每个被遍历到的节点
list_for_each_entry_safe(type *cursor,
type *tmp;
struct list_head *list,
member);
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对本站的支持。如果你想了解更多相关内容请查看下面相关链接