【问题标题】:Linux kernel module programmingLinux内核模块编程
【发布时间】:2015-09-21 18:34:04
【问题描述】:

这是我第一次在这里发布问题,所以要温柔。 我正在深入研究有趣的操作系统世界,并想尝试编写一个 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 内核定义了一个双向链表数据结构。我怀疑这里的内核代码中是否存在实际错误,并且我怀疑我只是在这里错误地使用了某些函数或宏。对于解决此问题的任何帮助,我将不胜感激。

谢谢, 帕夫

【问题讨论】:

    标签: c linux-kernel operating-system linux-device-driver


    【解决方案1】:

    两个问题:

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

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

    所以这应该有效:

    #include <linux/list.h>
    
    struct birthday {
        int day;
        int month;
        int year;
        struct list_head list;
    };
    

    【讨论】:

    • 我没有更改 Q 中的结构顺序。诚然,我不确定为什么将 struct list_head 放在第一位很重要。你能详细说明一下吗?
    • 以上是我回复评论的内容,基本上是说将list_head放在结构的开头很重要。该评论随后以某种方式被删除。
    • 它使指针运算更容易:container_of() 将仅用于静态转换。
    猜你喜欢
    • 2011-05-03
    • 1970-01-01
    • 2017-10-01
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    相关资源
    最近更新 更多