一个驱动程序管理多个设备,可能需要在驱动程序中跟踪每个设备,这就需要链表。
为了支持链表,代码中要添加头文件<linux/list.h>. 内核中链表实现核心部分的数据是struct list_head,其定义如下:
struct list_head{
struct list_head *next, *prev;
};
struct list_head 用在链表头和每个节点中。在内核中,将数据结构表示为链表之前,该结构必须嵌入struct lisg_head字段。例如,我们来创建car链表:
struct car{
int door_number;
char *color;
char *model;
};
在创建car链表之前,必须修改其结构,嵌入struct list_head字段。结构变成如下格式:
struct car{
int door_number;
char *color;
char *model;
struct list_head list; /*内核的链表结构*/
};
创建struct list_head变量,该变量总是指向链表的头部(第一个元素)。list_head这个实例与任何car变量都无关,而是一个特殊的实例:
static LIST_HEAD(carlist);
生成双向链表的头结点——LIST_HEAD(name)
LIST_HEAD(name) -- 生成一个名为name的双向链表头节点
#define LIST_HEAD(name) \
struct list_head name = LIST_HEAD_INIT(name)
static inline void INIT_LIST_HEAD(struct list_head *list)
{undefined
list->next = list;
list->prev = list;
}
#include<linux/list.h>
struct car *redcar = kmalloc(sizeof(*car), GFP_KERNEL);
struct car *bluecar = kmalloc(sizeof(*car), GFP_KERNEL);
//初始化每个节点的列表条目
INIT_LIST_HEAD(&bluecar->list);
INIT_LIST_HEAD(&redcar->list);
//为颜色和模型字段分配内存,并填充每个字段
list_add(&redcar->list, &carlist);
list_add(&bluecar->list, &carlist);
现在,carlist包含两个元素。
接下来深入介绍链表API,Linux内核链表(2)
list_head详细介绍请移步下面的链接: