Linux的模块开发注意
一、模块
Linux模块是linux的特色,他可以在需要的时候动态加载进内核,也可以在合适的时候移除内核,这样就保证内核的简洁高效
二、代码分析
#include <linux/init.h>
#include <linux/module.h>
static int hello_init(void)
{
return 0;
}
static void hello_exit(void)
{
}
module_init(hello_init);
module_exit(hello_exit);
重要的三个段:
1、
#include <linux/init.h>
#include <linux/module.h>
这两个头文件很重要,一定要包含住
2、
module_init(init_function);
初始化注册
3、
module_exit(exit_function);
退出注册
一般init_fuction形式是static int init();而exit_fuction形式为static void exit();
三、编译
使用makefile进行模块编译,在进行编译之前,需要先进入内核代码目录编译内核和模块,分别使用make zImage和make modules,之后会在目录/lib/modules/下生成linux***的目录,这个目录下的子目录build很重要,在我们模块编译中需要。
Makefile代码:
obj -m :=helloworld.o
helloworld -objs :=test1.o test2.o
KDIR :=/lib/modules/linux***/build
all:
make -C $(KDIR) M=$(PWD) modules
由test1.c和test2.c生成helloworld.ko模块
四、导出符号
一个模块mod1中定义一个函数func1;在另外一个模块mod2中定义一个函数func2,func2调用func1。
在模块mod1中,EXPORT_SYMBOL(func1);
在模块mod2中,extern int func1();
就可以在mod2中调用func1了。
五、内核声明
MODULE_AUTHOR(“XIN WEI <**@gmail.com>”); //作者
MODULE_LICENSE(“GPL v2”); //GPL 版本
MODULE_DESCRIPTION(“a test module”); //模块描述
MODULE_ALIAS(“A simple module”); //模块别名
六、加载
加载模块:insmod helloworld.ko 或者 modprobe helloworld.ko
卸载模块:rmmod helloworld.ko 或者 modprobe -r helloworld.ko
查看模块:lsmod
Reference: