list_for_each與list_for_each_entry具體解釋


一、list_for_each

1.list_for_each原型
#define list_for_each(pos, head) \
    for (pos = (head)->next, prefetch(pos->next); pos != (head); \
    pos = pos->next, prefetch(pos->next))
它實際上是一個 for 循環。利用傳入的pos 作為循環變量,從表頭 head開始,逐項向后(next方向)移動 pos ,直至又回到 head (prefetch() 能夠不考慮。用於預取以提高遍歷速度)。
注意:此宏必要把list_head放在數據結構第一項成員,至此。它的地址也就是結構變量的地址。

2.用法(以訪問當前進程的子進程為例):

struct list_head {
 struct list_head *next, *prev;
};

在struct task_struct 中有例如以下定義:
struct list_head children;

所以

struct task_struct *task;

struct list_head *list;

list_for_each(list,&current->chilidren) {

              task = list_entry(list, struct task_struct, sibling);/*task指向當前的某個子進程*/

}

當中用到了函數list_entry():
這個函數的作用在圖1中表示就是能夠通過已知的指向member子項的指針,獲得整個結構體的指針(地址)
#define list_entry(ptr, type, member) \
        container_of(ptr, type, member)

二、list_for_each_entry:
在Linux內核源代碼中,常常要對鏈表進行操作。當中一個非常重要的宏是list_for_each_entry:
意思大體例如以下:
如果僅僅有兩個結點,則第一個member代表head,
list_for_each_entry的作用就是循環遍歷每個pos中的member子項。
圖1:
pos:                                                           pos:
___________                                        ____________
|                       |                                     |                          |
|                       |                                     |                          |
|    ...........        |                                     |   ................       |
|                       |                        


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM