您的位置:首页 > 运维架构 > Linux

linux内核模块的安装与卸载

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

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模块已被成功卸载。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: