Linux内核模块编程

Linux kernel module programming

这是我第一次在这里发帖提问,请多多关照。 我正在钻研有趣的操作系统世界,想尝试编写一个 linux 内核模块。我在有关该主题的教科书中遇到了这个练习,并在 C 中编写了以下代码:

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

struct birthday {
    int day;
    int month;
    int year;
    struct list_head list;
}

static LIST_HEAD(birthday_list);

int simple_init(void) {
    struct birthday *ptr;
    int i;
    for(i = 0; i < 5; i++) {
        // create 5 birthday structs and add them to the list

        struct birthday *person;
        person = kmalloc(sizeof(*person), GFP_KERNEL);
        person->day = 22;
        person->month = 11;
        person->year = 1981;
        INIT_LIST_HEAD(&person->list);

        list_add_tail(&person->list, &birthday_list);
    }

    list_for_each_entry(ptr, &birthday_list, list) {
        // print the info from the structs to the log
        printk(KERN_INFO "%d, %d %d", ptr->month, ptr->day, ptr->year);
    }

    return 0;
}


void simple_exit(void) {
    struct birthday *ptr, *next;
    list_for_each_entry_safe(ptr, next, &birthday_list, list) {
        // delete structs and return memory
        list_del(&ptr->list);
        kfree(ptr);
    }
}

module_init(simple_init);
module_exit(simple_exit);

我遇到的问题是上面的代码无法编译,并且出现以下错误:

In file included from /home/parv112281/Documents/operating-systems/chap-2/list-struct/list-struct.c:1:0:
include/linux/list.h:22:2: error: expected ‘;’, identifier or ‘(’ before ‘struct’
  struct list_head name = LIST_HEAD_INIT(name)
  ^
/home/parv112281/Documents/operating-systems/chap-2/list-struct/list-struct.c:15:8: note: in expansion of macro ‘LIST_HEAD’
 static LIST_HEAD(birthday_list);
        ^
make[2]: *** [/home/parv112281/Documents/operating-systems/chap-2/list-struct/list-struct.o] Error 1
make[1]: *** [_module_/home/parv112281/Documents/operating-systems/chap-2/list-struct] Error 2
make[1]: Leaving directory `/usr/src/linux-headers-3.16.0-30-generic'
make: *** [all] Error 2

编译器似乎抱怨的错误是在 list.h 头文件中,该文件为 linux 内核定义了双向链表数据结构。我怀疑这里的内核代码是否存在实际错误,我怀疑我只是错误地使用了某些函数或宏。如果能帮我解决这个问题,我将不胜感激。

谢谢, 帕夫

两个问题:

  1. 使用内核链表需要包含linux/list.h

  2. 你忘了一个;声明结构生日时。

所以这应该有效:

#include <linux/list.h>

struct birthday {
    int day;
    int month;
    int year;
    struct list_head list;
};