linux中的部分宏
2016-01-31 17:24
441 查看
链表
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)
![](http://images2015.cnblogs.com/blog/578455/201601/578455-20160131172306661-2105504300.png)
注意:为什么能这么实现,跟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)
相关文章推荐
- linux下安装protobuf教程+示例(详细)
- Linux下Mysql简单操作
- CentOS6.5下Git服务器搭建
- linux下删除指定文件之外的其他文…
- CentOS Linux安装Atomic源(yu…
- linux下vi/vim 中文汉字乱码解决
- centos关机与重启命令详解
- linux下rar包的压缩与解压方案(转)
- centos的软件安装方法rpm和yum
- CentOS 6.2 yum安装配置…
- Linux 图形界面与命令行模式…
- 实例浅关-自增自减
- CentOS 6.5 安装OSA监控精灵监控主机
- linux下常用的几个时间函数:time,gettimeofday,clock_gettime,_ftime
- linux中的阻塞机制及等待队列
- Linux学习:第九周
- Linux学习笔记(4)----连接文件 ln
- centos6.5 安装 xtables-addons 过程及报错解决
- linux之链表和哈希表应用浅析一
- Linux操作系统Swapping(交换)