Linux 中 struct list_head 用法
头文件
#include <linux/list.h>
struct list_head简化定义
struct list_head {
struct list_head *next, *prev;
};
声明和初始化链表头
方法一
#include <linux/list.h>
LIST_HEAD(my_list);
方法二
struct list_head my_list;
INIT_LIST_HEAD(&my_list);
list_head放入到结构体中
struct man_info {
int id;
char *name;
struct list_head list;
};
添加节点到链表 list_add_tail
struct man_info *node = kmalloc(sizeof(struct man_info), GFP_KERNEL);
INIT_LIST_HEAD(&node->list);
node->id = 123;
node->name = "SDJMCGSJZY";
list_add_tail(&node->list, &my_list)
遍历链表
struct list_head *pos;
list_for_each(pos, &man_info) {
struct man_info *n = list_entry(pos, struct man_info, list);
printk(KERN_INFO "ID: %d, Name: %s\n", n->id, n->name);
}
struct list_head *pos, *tmp;
list_for_each_safe(pos, tmp, &my_list) {
struct my_data *n = list_entry(pos, struct my_data, list);
}
删除节点
list_del
list_del 将节点从链表中移除,但不初始化节点的 next 和 prev 指针;
list_del_init
list_del_init 将节点从链表中移除并且还会将节点的 next 和 prev 指针初始化为指向自己,这样节点就可以被安全地重新添加到链表中,而无需再次调用 INIT_LIST_HEAD。
list_del(&node->list);
list_del_init(&node->list);