Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

內核鏈表與普通鏈表差在哪?一次看懂 list_head 的設計巧思

內核鏈表本質上是雙向鏈表,但與教科書上的雙向鏈表有個關鍵差異:它的鏈表元素不綁定任何特定型別,因此具備通用性。

內核鏈表與普通鏈表差在哪?一次看懂 list_head 的設計巧思

上圖中 kernel list 是內核鏈表,normallist 是傳統鏈表,head 為鏈表頭,p1、p2、p3 為節點。差別在於指標指向的位置:傳統鏈表中,p1 的 next 指向 p2 這個結構體的開頭,p2 的 pre 指向 p1 結構體的開頭;而內核鏈表中,p1 的 next 指向的是 p2 結構體裡「list_head 那一段」的位址,p2 的 pre 同理指向 p1 中 list_head 的位址。

正因為指標只指向內嵌的 list_head 而非整個結構體,任何型別的結構體都能透過加入一個 list_head 成員而成為鏈表節點,這就是內核鏈表通用性的來源。代價是取用真正的資料時必須換算,而這件事正好由 list_entry(即 container_of)完成。

一個可運行的核心模組範例

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/list.h>

MODULE_LICENSE("GPL");
MODULE_AUTHOR("David Xie");
MODULE_DESCRIPTION("ListModule");
MODULE_ALIAS("List module");

struct student {
    char name[100];
    int num;
    struct list_head list;      /* 關鍵:把鏈表節點嵌進自己的結構體 */
};

struct student *pstudent;
struct student *tmp_student;
struct list_head student_list;
struct list_head *pos;

int mylist_init()
{
    int i = 0;
    INIT_LIST_HEAD(&student_list);
    pstudent = kmalloc(sizeof(struct student) * 5, GFP_KERNEL);
    memset(pstudent, 0, sizeof(struct student) * 5);

    for (i = 0; i < 5; i++) {
        sprintf(pstudent[i].name, "Student%d", i + 1);
        pstudent[i].num = i + 1;
        list_add(&(pstudent[i].list), &student_list);
    }

    list_for_each(pos, &student_list) {
        tmp_student = list_entry(pos, struct student, list);
        printk("<0>student%d name: %s\n", tmp_student->num, tmp_student->name);
    }
    return 0;
}

void mylist_exit()
{
    int i;
    for (i = 0; i < 5; i++)
        list_del(&(pstudent[i].list));
    kfree(pstudent);
}

module_init(mylist_init);
module_exit(mylist_exit);

程式的重點有三處:INIT_LIST_HEAD 初始化鏈表頭;list_add 把每個 student 的 list 成員掛上鏈表;list_for_each 搭配 list_entry 從 list_head 還原出外層的 struct student,才能印出真正的 name 與 num。若少了 list_entry 這一步,手上永遠只有一個與業務无关的 list_head。

Copyright © Linux教程網 All Rights Reserved