Linux内核的宏list分析

linux中的部分宏

链表

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

链表声明

#define LIST_HEAD_INIT(name) {&(name),&(name)}
================================================
1.静态初始化
#define LIST_HEAD(name)
    struct list_head name = LIST_HEAD_INIT(name)
================================================= 
LIST_HEAD(list_name); 
==>
    struct list_head list_name = LIST_HEAD_INIT(name);
==>
    struct list_head list_name = {&(list_name), &(list_name)};
    //相当于给一个结构声明加初始化,让list_name的成员变量
    //【next,prev】 = {&(list_name), &(list_name)}

2.运行时初始化
stattic inline void INIT_LIST_HEAD(struct list_head *list)
{
    list->next = list;
    list->prev = list;
}

链表是否为空

static inline int list_empty(const struct list_head* head)
{
    return head->next == head;
}

链表插入

1.插入head后
static inline void list_add(struct list_head* new, struct list_head* head)
{
    __list_add(new, head, head->next);
}

2.插入head->prev后

static inline void list_add_tail(struct list_head* new, struct list_head* head)
{
    __list_add(new, head->prev, head);
}

删除

static inline void list_replace_init(struct list_head *old, struct list_head *new)
{
    list_replace(old,new);
    INIT_LIST_HEAD(old);
}

遍历

#define list_entry(ptr, type, member) \
    container_of(ptr, type, member)

#define container_of(ptr, type, member) \
{\
    const typeof( ((type *)0)->member ) *__mptr = (ptr);\
    (type *)( (char *)__mptr - offsetof(type,member) ); \
}

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

在这里插入图片描述

注意:为什么能这么实现,跟C语言特性很有关系,在C中,给定的结构中,成员的偏移在编译时被固定下来了。

遍历链表:
宏:list_for_each()

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

pos是迭代指针,指向当前访问的链表头。
head是要访问的链表的链表头。

结合list_entry使用,就可以访问链表头所在元素了。
list_for_each(p,&elem_list){
    f = list_entry(p, struct elem, list);
}

更简单使用:
宏:list_for_each_entry(pos,head,member)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值