Linux内核数据结构(2.6.32.27)链表

来源:互联网 发布:中国酒类行业产量数据 编辑:程序博客网 时间:2024/06/07 12:38

Linux内核双向链表的实现不是将结构嵌入链表,而是将链表节点嵌入结构 

一、Linux内核中链表的实现

1.链表数据结构 双向循环链表

数据结构是struct list_head类型 在<linux/list.h>中

/* * Simple doubly linked list implementation. * * Some of the internal functions ("__xxx") are useful when * manipulating whole lists rather than single entries, as * sometimes we already know the next/prev entries and we can * generate better code by using them directly rather than * using the generic single-entry routines. */struct list_head {struct list_head *next, *prev;};

container_of()宏,获取父结构的地址<linux/kernel.h>

/** * 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) );})

offsetof(TYPE, MEMBER)宏 <linux/stddef.h>

#undef offsetof#ifdef __compiler_offsetof#define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER)#else#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)#endif


list_entry() 宏,返回包含list_head的父类型结构体指针,而不需要知道list_head所嵌入对象的数据结构 <linux/list.h>

/** * 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)

2.定义一个链表

 动态创建  用到INIT_LIST_HEAD(&red_fox->list)

static inline void INIT_LIST_HEAD(struct list_head *list){list->next = list;list->prev = list;}


静态创建 用到LIST_HEAD_INIT(red_fox.list)

#define LIST_HEAD_INIT(name) { &(name), &(name) }


3.链表头

这个宏定义表头

#define LIST_HEAD(name) \struct list_head name = LIST_HEAD_INIT(name)

二、操作链表

1.向链表中增加一个节点

list_add  添加后还是双向循环链表

/* * Insert a new entry between two known consecutive entries. * * This is only for internal list manipulation where we know * the prev/next entries already! */#ifndef CONFIG_DEBUG_LISTstatic inline void __list_add(struct list_head *new,      struct list_head *prev,      struct list_head *next){next->prev = new;new->next = next;new->prev = prev;prev->next = new;}#elseextern void __list_add(struct list_head *new,      struct list_head *prev,      struct list_head *next);#endif/** * list_add - add a new entry * @new: new entry to be added * @head: list head to add it after * * Insert a new entry after the specified head. * This is good for implementing stacks. */static inline void list_add(struct list_head *new, struct list_head *head){__list_add(new, head, head->next);}


list_add_tail就是  __list_add(new, head->prev, head)

2.链表中删除一个节点

list_del  <linux/list.h>   <../lib/list_debug.c>

0 0
原创粉丝点击