首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Linux内核模块编程

Linux内核模块编程
EN

Stack Overflow用户
提问于 2015-07-03 22:35:58
回答 1查看 2.5K关注 0票数 2

这是我第一次在这里发表一个问题,所以请温柔一点。我正在深入研究操作系统的有趣世界,并想尝试尝试编写linux内核模块。我在一本有关这一主题的教科书中看到了这个练习,并用C编写了以下代码:

代码语言:javascript
复制
#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);

我遇到的问题是上面的代码不会编译,我会得到以下错误:

代码语言:javascript
复制
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内核定义了一个双链接列表数据结构。我怀疑这里的内核代码中有一个实际的错误,我怀疑我只是在这里不正确地使用某些函数或宏。如果能帮忙解决这个问题,我将不胜感激。

谢谢你,帕夫

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-07-03 23:29:07

两个问题:

  1. 要使用内核链接列表,需要包含linux/list.h
  2. 你在宣布组织生日时忘了一个。

所以这应该是可行的:

代码语言:javascript
复制
#include <linux/list.h>

struct birthday {
    int day;
    int month;
    int year;
    struct list_head list;
};
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31214909

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档