linux内核模块的安装与卸载

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模块已被成功卸载。
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值