Linux内核的Container_of机制
来源:互联网 发布:python sin函数图像 编辑:程序博客网 时间:2024/04/25 19:27
在内核的原码文件 kernel.h文件中,定义了一个宏container_of,如下:
/** * container_of - cast a member of a structure out to the containing structure * @ptr:the pointer to the member. * @type:the type of the container struct this is embedded in. * @member:the name of the member within the struct. * */#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) //这个宏不是在kernel.h文件中定义的。
ptr:指向成员的指针。
type:需要返回的结构实例类型。
member:成员在结构实例内部的名称,如果为数组,需要指定下标。
下面分析一下这个宏,举个例子:
假设下面的这个结构:
struct pid{atomic_t count;/* lists of tasks that use this pid */struct hlist_head tasks[PIDTYPE_MAX];struct rcu_head rcu;int level;struct upid numbers[4];};最后一个本来不是4,而是1,我为了便于理解,将其改成4。
我们的需求是:根据结构体内的struct upid number[2]来获取这个结构实例的指针,假设已经知道struct upid number[2]的指针是pnr,如下定义:
按照这个宏的定义目标,我们可以这么实现:
struct upid *pnr;struct pid *_pid = container_of(pnr, struct pid,numbers[ns->level]); //根据struct upid numbers[ns->level]来返回struct pid的实例指针。
offsetof宏:先将空指针0转换为一个指向struct pid的指针,然后获取成员的地址,因为是从0开始的,所以这个地址就是成员相对于struct pid结构的偏移量。
因为内存的使用是往上增长的,所以成员自己的地址减去成员在结构中的偏移量就是结构实例的地址了。
这个宏是内核的一个使用技巧,很多地方都是这样根据成员的地址然后找到结构实例的地址。
- Linux内核的Container_of机制
- linux内核链表宏 container_of的详细推导
- 【转】Linux内核的container_of宏
- 对linux内核宏container_of的理解
- Linux内核中container_of宏的理解
- 对linux内核宏container_of的理解
- Linux内核中container_of宏的理解
- linux内核的container_of()宏定义分析
- Linux内核中container_of宏的理解
- linux内核中container_of的理解
- 关于linux内核container_of宏的理解
- hlist_head和list_head区别以及container_of机制 - [linux内核]
- Linux内核中的container_of()
- Linux内核container_of宏
- linux内核中的container_of
- Linux内核基础-container_of
- linux内核container_of详解
- linux内核中container_of
- storm开源介绍
- paramiko的安装与使用
- execute、executeQuery和executeUpdate之间的区别
- ZENCART SEO优化细节建议
- adduser添加(创建)用户和终端方向键tab键不能用的解决(在ubuntu11上验证)
- Linux内核的Container_of机制
- webkit中的javascript(4)---javascript执行的入口
- android.graphics.Bitmap.Config<ALPHA_8, ARGB_4444,ARGB_8888,RGB_565>
- 基于Spring JdbcTemplate 的分页处理
- django中自定义orm,修改默认规则
- iframe自动高度 12306
- 在 NetBeans IDE 中调试 PHP 源代码
- django的通用视图 (generic views)
- 破解工具