1. 内核链表是特殊的双向循环链表,链表节点如下:
struct list_head
{
struct list_head *next,*prev;
};
2. 内核链表-函数
1. INIT_LIST_HEAD: 初始化链表
2. list_add: 在链表头插入节点
3. list_add_tail: 在链表尾插入节点
4. list_del: 删除节点
5. list_entry: 取出节点
6. list_for_each: 遍历链表
3. 内核链表实现分析
内核链表在头文件 <linux/list.h>中声明
struct score
{
int num;<span style="white-space:pre"> </span> /* 编号 */
int english; /* 英语成绩 */
int math; /* 数学成绩 */
struct list_head list; /* 链表节点 */
};
上面结构中,score中的list.next指向下一个链表节点,list.prev指向前一个链表节点
问题是我们怎样通过链表节点找到父结构中包含的其他变量呢?
/**
* list_entry - get the struct for this entry
* @ptr: the &struct list_head pointer.
* @type: the type of the struct this is embedded in.
* @member: the name of the list_struct within the struct.
*/
#define list_entry(ptr, type, member) \
container_of(ptr, type, member)
/**
* container_of - cast a member of a structure out to the containing structure
* @ptr: the pointer to the member.
* @type: the type of the container struct this is embedded in.
* @member: the name of the member within the struct.
*
*/
#define container_of(ptr, type, member) ({ \
const typeof(((type *)0)->member) * __mptr = (ptr); \
(type *)((char *)__mptr - offsetof(type, member)); })
在c语言中,一个给定结构中的变量偏移在编译时就已经固定下来了,使用宏container_of()可以方便的从链表指针找到父结构中包含的变量
深入理解container_of: typeof是GNU C对标准C的扩展,作用是获取变量的类型,(type*)0;就是假设地址0处存放的是一个type类型的结构体变量,这一行是先取member的类型,然后再定义一个此类型的指针变量_mptr,并将链表节点的指针变量赋值给它,使用const是确保此处定义的指针变量不会被修改,增强了安全性。
(char*)_mptr转化成字节型指针,(char*)_mptr-offsetof(type,member)用来求出结构体的起始地址,然后又被转化为type*类型。
再来分析offsetof,这也是一个宏 :
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
&((TYPE*)0->MEMBER)就是MEMBER的地址,而基地址已设为0,这样转化为了TYPE的偏移量,然后强制转化为tsize_t类型,即int型。
4.内核链表的使用
#include <linux/module.h>
#include <linux/init.h>
#include <linux/list.h>
struct score
{
int num;
int english;
int math;
struct list_head list;
};
struct list_head score_head;
struct score stu1,stu2,stu3;
struct list_head *pos;
struct score *tmp;
int mylist_init()
{
INIT_LIST_HEAD(&score_head);
stu1.num = 1;
stu1.english = 90;
stu1.math = 98;
list_add_tail(&(stu1.list),&score_head);
stu2.num = 2;
stu2.english = 92;
stu2.math = 91;
list_add_tail(&(stu2.list),&score_head);
stu3.num = 3;
stu3.english = 94;
stu3.math = 95;
list_add_tail(&(stu3.list),&score_head);
list_for_each(pos,&score_head)
{
tmp = list_entry(pos,struct score,list);
printk(KERN_WARNING"No %d,english is %d,math is %d\n",tmp->num,tmp->english,tmp->math);
}
return 0;
}
void mylist_exit()
{
list_del(&(stu1.list));
list_del(&(stu2.list));
}
module_init(mylist_init);
module_exit(mylist_exit);
运行结果:
# insmod mylist.ko
No 1,english is 90,math is 98
No 2,english is 92,math is 91
No 3,english is 94,math is 95