Linux内核链表主要用于内核驱动程序中跟踪每个设备。内核中只实现了双向链表。
本笔记只简单记录如何创建链表,向链表中添加节点,删除节点,遍历链表。
1.使用内核链表需要包含的头文件:
#include <linux/list.h>
在内核中,将数据结构表示为链表之前,该结构必须嵌入struct list_head 字段
struct car {
int door_num; //自定义字段
char *color; //自定义字段
char *model; //自定义字段
struct list_head list; /*内核的表结构,必须加入此结构才能构建内核链表*/
}
创建struct list_head 变量,该变量总是指向链表的头部(第一个元素)与任何实例无关,是一个特殊的实例。
static LIST_HEAD(mylist);
创建链表节点:
struct car *redcar = kmalloc(sizeof(struct car), GFP_KERNEL);
struct car *bluecar= kmalloc(sizeof(struct car), GFP_KERNEL);
初始化每个节点
INIT_LIST(&bluecar->list);
INIT_LIST(&redcar->list);
为每个节点分配内存,并填充每个字段。把节点添加到链表中
list_add(&redcar->list, &mylist);
list_add(&bulecar->list, &mylist);
完整实例如下:
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/init.h>
#include <linux/delay.h> //msleep
#include <linux/slab.h>
#include <linux/compiler.h>
#include <linux/module.h>
typedef struct car{
int door_num;
char color[32];
char model[32];
struct list_head list; //必须嵌入此结构才能使用内核链表
} Car, *CAR;
/*静态初始化只需要下面一条语句即可完成(推荐)*/
//LIST_HEAD(mylist);
//使用内核的宏定义【动态创建和初始化】一个内核链表
struct list_head mylist;
struct car *acar; /*内核链表遍历用的循环计数器,类似于for(i=0; i<num; i++)循环的变量 i*/
/*驱动程序入口函数*/
static int __init list_init(void){
INIT_LIST_HEAD(&mylist);
/*为内核链表申请节点*/
struct car *blackCar;
struct car *redCar;
struct car *blueCar;
blackCar = kmalloc(sizeof(Car), GFP_KERNEL);
redCar = kmalloc(sizeof(Car), GFP_KERNEL);
blueCar = kmalloc(sizeof(Car), GFP_KERNEL);
/*初始化链表节点,使其指向自身*/
INIT_LIST_HEAD(&mylist);
INIT_LIST_HEAD(&blackCar->list);
INIT_LIST_HEAD(&redCar->list );
INIT_LIST_HEAD(&blueCar->list );
/*填充链表节点内容*/
blackCar->door_num = 100;
memcpy(blackCar->color, "black", sizeof("black") );
redCar->door_num = 101;
memcpy(redCar->color, "red", sizeof("red") );
blueCar->door_num = 102;
memcpy(blueCar->color, "blue", sizeof("blue") );
/*添加链表节点到内核链表*/
list_add(&blackCar->list, &mylist);
list_add(&redCar->list, &mylist);
list_add(&blueCar->list, &mylist);
/*内核链表的遍历*/
list_for_each_entry(acar, &mylist, list){
printk("acar->door_num=[%d]--acar->color=[%s]\n", acar->door_num, acar->color);
}
/*删除其中一个节点*/
list_del(&blackCar->list);
//分配给该节点的内存需要手动释放
kfree(blackCar);
printk("after del blackCar");
/*内核链表再次遍历*/
list_for_each_entry(acar, &mylist, list){
printk("acar->door_num=[%d]--acar->color=[%s]\n", acar->door_num, acar->color);
}
return 0;
}
/*驱动程序退出函数*/
static void __exit list_exit(void){
printk("list module exited\n");
list_for_each_entry(acar, &mylist, list){
kfree(acar);
}
return;
}
/*驱动入口*/
module_init(list_init);
module_exit(list_exit);
MODULE_LICENSE("GPL");
#
# @Makefile
# 内核module编译
#
obj-m +=list.o
kernel_rel:=`uname -r`
linux_path=/lib/modules/`uname -r`/build
current_dir=$(shell pwd)
all:
make -C $(linux_path) M=$(current_dir) modules
#注意tab
clean:
make -C $(linux_path) M=$(current_dir) clean
2.注意点:
未初始化的节点,可能被初始化未null。