Linux的链表结构

来源:互联网 发布:限制流量的软件 编辑:程序博客网 时间:2024/05/16 12:07

内核中链表的实现位于 include/linux/list.h 文件,链表数据结构的定义也很简单。

21 struct list_head{22 structlist_head *next,*prev;23};


list_head 结构包含两个指向 list_head 结构的指针 prev 和 next,由此可见,内核中的链表实际上都是双链表(通常都是双循环链表)。通常,我们在数据结构课堂上所了解的链表定义方式是这样的(以单链表为例) :
struct list_node { struct list_node *next;  ElemType data;};


通过这种方式使用链表,对每一种数据类型,都要定义它们各自的链表结构。而内核中的链表却与此不同,它并没有数据域,不是在链表结构中包含数据, 是而在描述数据类型的结构中包含链表。

(5)遍历。

内核中的链表仅仅保存了 list_head 结构的地址,我们如何通过它或取一个链表节点真正的数据项?这就要提到有关链表的所有操作里面,最为重要 超级经典的 list_entry 宏了,我们可以通过它很容易地获得一个链表节点的数据。
#define list_entry(ptr,type,member)\
 container_of(ptr,type,member)


关于 list_entry(),让我们结合实例来看,还是 hub 驱动的那个例子,当我们真的要处理 hub 的事件的时候,我们当然需要知道具体是哪个 hub 触发了这起事

件。而 list_entry 的作用就是,从 struct list_head event_list 得到它所对应的struct usb_hub 结构体变量。比如以下四行代码:

struct list_head *tmp;
 struct usb_hub *hub;
 tmp=hub_event_list.next;
 hub=list_entry(tmp,struct usb_hub,event_list);
从全局链表 hub_event_list 中取出一个来,叫做 tmp,然后通过 tmp,获得它所对应的 struct usb_hub。


0 0
原创粉丝点击