Linux内核模块程序加载方法

Linux提供了一种动态加载内核的机制,这种机制称为模块(Module),模块具有一下特点:
1、模块本身不被编译入内核映像,从而控制了内核的大小。
2、模块一旦被加载,它就和内核中的其它部分完全一样。
为了方便理解,下面从一个最简单的内核模块“Hello World” 开始。
(我的环境是:Ubuntu9.10 , linux-source-2.6.31)

1、在/home/china/test中编写hello.c文件
如下:
#include<linux/init.h>
#include<linux/module.h>
MODULE_LICENSE("Dual BSD/GPL");  //声明GPL版权

static int hello_init(void)         //加载
{
printk(KERN_ALERT "Hello World enter\n");
return 0;

}

static void hello_exit(void)     //卸载
{
printk(KERN_ALERT "Hello World exit\n");

}

module_init(hello_init);
module_exit(hello_exit);
写好后保存退出;
2、同一目录下编写Makefile
obj-m :=hello.o
保存退出;

3、使用如下命令编译hello模块
make -C  /usr/src/linux-headers-2.6.31-21-generic  M=$(pwd)  modules
(注:-C后为系统内核存放路径,M后为hello.c源文件路径,因为在test目录下,所以用$(pwd)代替,如果不做该目录下,则要写全源文件的路径)
4、编译结果如下:

make:进入目录‘/usr/src/linux-headers-2.6.31-21-generic‘
  CC [M]  /home/china/test/hello.o
  Building modules, stage 2.
  MODPOST 1 modules
  CC      /home/china/test/hello.mod.o
  LD [M]  /home/china/test/hello.ko
make:离开目录“/usr/src/linux-headers-2.6.31-21-generic”

5、在test目录下你会看到生成了如下文件

hello.c   hello.mod.c  hello.o     modules.order
hello.ko  hello.mod.o  Makefile  Module.markers  Module.symvers
其中hello.ko就是模块目标文件,
6、将hello.ko加载进内核
在终端下输入如下命令: sudo insmod  ./hello.ko
查看加载的内容:           sudo dmesg | tail -n 1 
此时输出信息:              Hello World enter
7、将hello.ko模块卸载
在终端下输入如下命令: sudo rmmod hello
查看卸载的内容:           sudo dmesg | tail -n 1 
此时输出信息:              Hello World exit
8、模块卸载以后,使用  lsmod | grep hello 命令查看模块列表,如果没有任何输出,表示hello模块已被成功卸载。

Linux内核模块程序加载方法,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。