1. 程式人生 > >linux核心連結串列list_entry()函式的分析

linux核心連結串列list_entry()函式的分析

這個函式可以通過list的指標域推算出它的節點所指向的值,具體程式碼實現如下:

/**
 * list_entry - get the struct for this entry
 * @ptr: the &struct list_head pointer.
 * @type: the type of the struct this is embedded in.
 * @member: the name of the list_struct within the struct.
 */
#define list_entry(ptr, type, member) \
 container_of(ptr, type, member)
/**
 * 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) );})

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

連結串列的結構可以表示成如下的形式:

p-------------------------->
pos------------------------> next
prev

關鍵就是看如何通過pos的地址算出p的地址,p指向連結串列的開頭。在這裡讓p的地址為0,那麼它裡面的成員member的地址就是偏移的大小,member就是list_head在成員中的名字。
ptr是list_head的地址,減去這個偏移就是節點的地址,取這個地址的內容就可以得到節點的值。