本文参考内核代码2.6.9 List.h中相关代码,如有疑问欢迎评论.

链表

链表是线性表的一种,可以高效地在链表中的任意位置实时插入、删除数据。链表的开销主要是访问的顺序性和组织链的空间损失.
通常链表数据结构至少应包含两个域:数据域和指针域,数据域用于存储数据,指针域用于建立与下一个节点的联系。
内核代码2.6.9中链表结构定义如下:

struct list_head {
    struct list_head *next, *prev;
};

这个结构跟我们之前看到的不太一样,没有数据域,这样做的好处是具备了通用型.
链表可以分为单链表、双链表、循环链表等多种类型,下面分别给出这几类链表类型的介绍:

单链表

单链表是最简单的一类链表,它的特点是仅有一个指针域指向后继节点(next),因此,对单链表的遍历只能从头至尾(通常是NULL空指针)顺序进行。

双链表

单链表中对于查找前驱节点,只能从头访问,双向链表是为了满足更加方便的查找前驱,而付出空间的代价的一个数据结构。
双向链表的节点定义如下:

typedef struct node
{
    int x;
    struct node *prior,*next;
}DLNode;

循环链表

循环链表的特点是尾节点的后继指向首节点,首节点的前驱指针指向尾节点.
在Linux内核中使用了大量的链表结构来组织数据,包括设备列表以及各种功能模块中的数据组织。这些链表大多采用在[include/linux/list.h]实现了一个相当精彩的链表数据结构。本文的后继部分就将通过示例详细介绍这一数据结构的组织和使用,并在文章末尾附上一个简单的例子。

在数据结构课本中,链表的经典定义方式通常是这样的(以单链表为例):

struct list_node {
    struct list_node *next;
    ElemType    data;
};

因为ElemType的缘故,对每一种数据项类型都需要定义各自的链表结构。有经验的C++程序员应该知道,标准模板库中的采用的是C++ Template,利用模板抽象出和数据项类型无关的链表操作接口。
在Linux内核链表中,需要用链表组织起来的数据通常会包含一个struct list_head成员,例如在[include/linux/netfilter.h]中定义了一个nf_sockopt_ops结构来描述Netfilter为某一协议族准备的getsockopt/setsockopt接口,其中就有一个(struct list_head list)成员,各个协议族的nf_sockopt_ops结构都通过这个list成员组织在一个链表中,表头是定义在[net/core/netfilter.c]中的nf_sockopts(struct list_head)。从下图中我们可以看到,这种通用的链表结构避免了为每个数据项类型定义自己的链表的麻烦。Linux的简捷实用、不求完美和标准的风格,在这里体现得相当充分。

链表操作

声明和初始化

#define LIST_HEAD_INIT(name) { &(name), &(name) }
#define LIST_HEAD(name) struct list_head name = LIST_HEAD_INIT(name)

当我们用LIST_HEAD(nf_sockopts)声明一个名为nf_sockopts的链表头时,它的next、prev指针都初始化为指向自己,这样,我们就有了一个空链表,因为Linux用头指针的next是否指向自己来判断链表是否为空:

/**
 * list_empty - tests whether a list is empty
 * @head: the list to test.
 */
static inline int list_empty(const struct list_head *head)
{
    return head->next == head;
}

除了用LIST_HEAD()宏在声明的时候初始化一个链表以外,Linux还提供了一个INIT_LIST_HEAD宏用于运行时初始化链表:

#define INIT_LIST_HEAD(ptr) do { \
    (ptr)->next = (ptr); (ptr)->prev = (ptr); \
} while (0)

看到内核代码中INIT_LIST_HEAD宏是不是觉得有点怪?
这么做的原因主要是避免宏在if else语句中所产生的分号吞噬问题,参考链接.
我们用INIT_LIST_HEAD(&nf_sockopts)来使用它。

插入 删除 合并

对链表的插入操作有两种:在表头插入和在表尾插入。Linux为此提供了两个接口:
static inline void list_add(struct list_head *new, struct list_head *head);
static inline void list_add_tail(struct list_head *new, struct list_head *head);
详细代码如下:

/*
 * Insert a new entry between two known consecutive entries.
 *
 * This is only for internal list manipulation where we know
 * the prev/next entries already!
 */
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_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 - add a new entry
 * @new: new entry to be added
 * @head: list head to add it before
 *
 * Insert a new entry before the specified head.
 * This is useful for implementing queues.
 */
static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
    __list_add(new, head->prev, head);
}

添加的话,看注释我们可以看到,这是已知要添加在哪两个节点前后,只需要修改4个指针即可.
发现如果函数名前有__表示:会被封装,一般不直接调用__list_add().
函数list_add_tail就是调用的__list_add(),是在head和head->prev之间插入新结点,因为head->prev就是双向循环链表的末尾结点,
因此该函数每次实在链表的末尾插入结点,实现的是队列的功能,即“先进先出”。就是传说中人们常说的尾插法.
而函数list_add则是在head 和 head->next之间插入元素,就是传说中的头插法.

/*
 * Insert a new entry between two known consecutive entries.
 *
 * This is only for internal list manipulation where we know
 * the prev/next entries already!
 */
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_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 - add a new entry
 * @new: new entry to be added
 * @head: list head to add it before
 *
 * Insert a new entry before the specified head.
 * This is useful for implementing queues.
 */
static inline void list_add_tail(struct list_head *_new, struct list_head *head)
{
    __list_add(_new, head->prev, head);
}

链表合并

/**
 * list_splice - join two lists
 * @list: the new list to add.
 * @head: the place to add it in the first list.
 */
static inline void list_splice(struct list_head *list, struct list_head *head)
{
    if (!list_empty(list))
        __list_splice(list, head);
}

/**
 * list_splice_init - join two lists and reinitialise the emptied list.
 * @list: the new list to add.
 * @head: the place to add it in the first list.
 *
 * The list at @list is reinitialised
 */
static inline void list_splice_init(struct list_head *list,
                    struct list_head *head)
{
    if (!list_empty(list)) {
        __list_splice(list, head);
        CFS_INIT_LIST_HEAD(list);
    }
}

内核链表操作实例:

#include<stdio.h>
#include<stdlib.h>

//链表头结构
struct list_head
{
    struct list_head *next,*prev;
};


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

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

#define list_for_each(pos,head) \
for(pos = (head)->next;pos != (head);pos = pos->next)

#define list_for_each_safe(pos,n,head) \
for(pos = (head)->next,n = pos->next;pos != (head);pos = n,n = pos->next)

//链表头初始化
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;
}

static inline void list_add(struct list_head *new, struct list_head *head)
{
    __list_add(new, head, head->next);
}
/**
 * list_add_tail - add a new entry
 * @new: new entry to be added
 * @head: list head to add it before
 *
 * Insert a new entry before the specified head.
 * This is useful for implementing queues.
 */
static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
    __list_add(new, head->prev, head);
}

//根据节点中的一个成员在节点中的偏移量找到节点的起始地址
#define list_entry(ptr,type,member) \
((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))

//真正实现链表删除操作
static inline void __list_del(struct list_head * prev, struct list_head * next)
{
    next->prev = prev;
    prev->next = next;
}

//删除链表中的一个节点
void list_del(struct list_head *entry)
{
    __list_del(entry->prev,entry->next);
    /*实际linux内核源码中next与prev设置的并非NULL*/
    entry->next = NULL;
    entry->prev = NULL;
}

//链表长度
#define N  10

//定义节点的数据结构
typedef struct numlist
{
    int num;//数据域
    struct list_head list;//链表域
}element;

int main()
{
    //定义链表头节点
    element numhead;
    element *listnode;
    struct list_head *pos;
    element *p;
    struct list_head *t;
    int i = 0;
    
    //初始化双向循环链表头节点
    INIT_LIST_HEAD(&numhead.list);
    
    for(i=0;i<N;i++)
    {
        //为新节点分配内存
        listnode = (element *)malloc(sizeof(element));
        //为节点数据域赋值
        listnode->num = i;
        //list_add头插法值9876543210,list_add_tail尾插法0123456789(队列)
        list_add_tail(&listnode->list,&numhead.list);
    }
    
    //遍历链表,可以看宏list_for_each的定义
    list_for_each(pos,&numhead.list)
    {
        /*通过链表返回指向结构体numlist的地址*/
        p = list_entry(pos,element,list);
        printf("Node %d's data: %d\n",9 - --i,p->num);
    }
    /*删除链表需使用list_for_each_safe*/
    list_for_each_safe(pos,t,&numhead.list)
    {
        //删除节点
        list_del(pos);
        p = list_entry(pos,element,list);
        //释放节点的内存
        free(p);
    }
    
    return 0;
}