链表有单链表,双链表,循环链表等
在内核中大量使用双向循环链表,在include/linux/list.h头文件实现
链表数据结构的定义:
struct list_head {
struct list_head *next, *prev;
};
此链表只有指针域没有数据域,与C语言传统的链表有区别。
因为每个对象的数据域可能不同,实现通用访问;
*初始化链表头
INIT_LIST_HEAD(list_head *head);
static inline void INIT_LIST_HEAD(struct list_head *list)
{
list->next = list;
list->prev = list;
}//链表的初始化,指向本身
*插入内核链表节点
list_add(struct list_head *new, struct list_head *head)
//在任意位置加入节点
list_add_tail(struct list_head *new, struct list_head *head)
//在链表尾加入节点
*删除内核链表节点
list_del(struct list_head *entry);
//注意删除后,该节点的指针也要赋值,避免成为野指针,不一样要立即释放
*提取链表数据结构
list_entry(ptr,type,member);
//返回的是这个结构类型的指针,这样就可以通过这个指针访问里面的成员了
ptr是指向这个list_head的指针,type是个结构的类型,member是这个内核链表的成员名
*遍历链表
#define list_for_each(pos, head) \
for (pos = (head)->next; prefetch(pos->next), pos != (head); \
pos = pos->next)
//pos是一个list_head型的指针,不用初始化
测试程序
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/list.h>
MODULE_LICENSE("GPL");
struct student
{
char name[100];
int num;
struct list_head list;
};
struct student *pstudent;
struct student *tmp_student;
struct list_head student_list;
struct list_head *pos;
int mylist_init()
{
int i = 0;
INIT_LIST_HEAD(&student_list);
pstudent = kmalloc(sizeof(struct student)*5,GFP_KERNEL);
memset(pstudent,0,sizeof(struct student)*5);
for (i =0;i <5;i++)
{
sprintf(pstudent[i].name,"Student",i+1);
pstudent[i].num = i+1;
list_add(&(pstudent[i].list),&student_list);
}
list_for_each(pos,&student_list)
{
tmp_student = list_entry(pos,struct student,list);
printk("<0>student %d name %s\n",tmp_student->num,tmp_student->name);
}
}
void mylist_exit()
{
int i;
for(i = 0;i < 5;i++)
{
list_del(&(pstudent[i].list));
}
kfree(pstudent);
}
module_init(mylist_init);
module_init(mylist_exit);