1.8 linux內核鏈表
1.8.1 內核鏈表簡介
鏈表是一種常用的數據結構,它通過指針將一系列數據節點連接成一條數據鏈。相對於數組,鏈表具有更好的動態性,建立鏈表時無需預先知道數據總量,可以隨機分配空間,可以高效地在鏈表中的任意位置實時插入或刪除數據。鏈表的開銷主要是訪問的順序性和組織鏈的空間損失。
1.8.2 內核鏈表結構
struct list_head{
struct list_head *next,*prev;
};
list_head結構包含兩個指向list_head結構的指針prev和next,由此可見,內核的鏈表具備雙鏈表功能,實際上,通常它都組織成雙向循環鏈表。
1.8.3 內核鏈表函數
//初始化鏈表
static inline void INIT_LIST_HEAD(struct list_head *list)
{
list->next = list;
list->prev = list;
}
//添加結點
static 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;
}
//刪除list結點
static inline void __list_del(struct list_head * prev, struct list_head * next)
{
next->prev = prev;
prev->next = next;
}
//刪除entry結點
static inline void list_del(struct list_head *entry)
{
__list_del(entry->prev, entry->next);
entry->next = LIST_POISON1;
entry->prev = LIST_POISON2;
}
//用新結點替換舊結點
static inline void list_replace(struct list_head *old,
struct list_head *new)
{
new->next = old->next;
new->next->prev = new;
new->prev = old->prev;
new->prev->next = new;
}
//遍歷結點信息
#define list_for_each_entry(pos, head, member) \
for (pos = list_entry((head)->next, typeof(*pos), member); \
&pos->member != (head); \
pos = list_entry(pos->member.next, typeof(*pos), member))
//計算結構信息結點的偏移量
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
//將結構的成員強制轉化爲包含結構
#define container_of(ptr, type, member) ({ \
const typeof(((type *)0)->member)*__mptr = (ptr); \
(type *)((char *)__mptr - offsetof(type, member)); })
內核鏈表具有通用性,就是在於它自定義了一個struct list_head類型的結構體,作爲鏈表的指針指向,然後,將用戶定義的鏈表結點包含該結構體,用戶鏈表的連接只需要使用struct list_head類型的結點指針進行連接,就有效的避免了不同類型鏈表結點導致,每個不同類型的結點,都必須針對其類型生成特定的鏈表處理函數。在內核鏈表中通過struct list_head類型的指針來連接鏈表中的各個結點,通過計算結點中有效信息部分的偏移量,再通過list_for_each_entry()這個函數達到訪問結點信息的目的。因此,即可實現只需要一套鏈表處理函數,就可以生成不同結點類型的鏈表。
1.8.4通過內核鏈表函數處理特定類型結點
#include<linux/module.h>
#include<linux/init.h>
#include<linux/list.h>
//特定信息鏈表結點類型
struct socre{
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 list_head *tmp;
int mylist_init(){
//鏈表初始化
INIT_LIST_HEAD(&score_head);
stu1.num=1;
stu1.english=98;
stu1.math=90;
//添加結點
list_add_tail(&(stu1.list),&score_head);
stu2.num=2;
stu2.english=91;
stu2.math=93;
list_add_tail(&(stu2.list),&score_head);
stu3.num=3;
stu3.english=96;
stu3.math=95;
list_add_tail(&(stu3.list),&score_head);
//遍歷結點信息
list_for_each(pos,&score_head){
tmp = list_entry(pos,struct score,list);
printk("Num is %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);