读书人

读书笔记以内核数据结构一链表

发布时间: 2012-09-21 15:47:26 作者: rapoo

读书笔记之内核数据结构一链表

在Linux内核中实现了几种常用的数据结构包括:链表、队列、映射、二叉树。

一、链表

在一般需要遍历所有数据或需要动态的加入和删除数据时选用链表比较适合,当需要随机访问数据时一般不使用链表。Linux内核中链表的实现不同于通常的设计,它不是将数据塞入链表,而是将链表节点塞入数据结构。

Linux中通过下面两个宏来实现:

#include <stdlib.h>#include <stdio.h>#include <assert.h>#define offsetof(TYPE,MEMBER) ((size_t)&((TYPE*)0)->MEMBER)#define container_of(ptr,type,member) ({ \const typeof(((type*)0)->member)*__mptr=(ptr);\(type*)((char*)__mptr-offsetof(type,member));})struct fox{int length;int weight;int member;};int main(){   int len;struct fox test;struct fox *ptest;test.length=3;test.weight=20;test.member=1;ptest=container_of(&test.member,struct fox,member);printf("%d\n",ptest->length);len=offsetof(struct fox,member);assert(len==8);printf("%d\n",len);    return 0;}
输出结果为

3

8



读书人网 >编程

热点推荐