|
#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 是否指向自己来判断链表是否为空:
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(&nf_sockopts) 来使用它。
2. 插入/删除/合并
a) 插入
对链表的插入操作有两种:在表头插入和在表尾插入。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);
|
因为 Linux 链表是循环表,且表头的 next、prev 分别指向链表中的第一个和最末一个节点,所以,list_add 和 list_add_tail 的区别并不大,实际上,Linux 分别用
__list_add(new, head, head->next);
|
和
__list_add(new, head->prev, head);
|
来实现两个接口,可见,在表头插入是插入在 head 之后,而在表尾插入是插入在 head->prev 之后。
假设有一个新 nf_sockopt_ops 结构变量 new_sockopt 需要添加到 nf_sockopts 链表头,我们应当这样操作:
list_add(&new_sockopt.list, &nf_sockopts);
|
从这里我们看出,nf_sockopts 链表中记录的并不是 new_sockopt 的地址,而是其中的 list 元素的地址。怎么样通过链表访问到 new_sockopt 呢?下面会有详细介绍。
b) 删除
static inline void list_del(struct list_head *entry);
|
共4页: 上一页 [1] 2 [3] [4] 下一页
|