打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Linux内核模块的编译、加载和卸载

 

转载请注明出处:http://blog.csdn.net/zhangyang0402/archive/2010/07/04/5711502.aspx

 

一、hello.c

 

  1. #include<linux/init.h>  
  2. #include<linux/module.h>  
  3.   
  4. MODULE_LICENSE("Dual BSD/GPL");  
  5.   
  6. static int hello_init(void)  
  7. {  
  8.         printk(KERN_ALERT "Hello, World! This is init./n");  
  9.         return 0;  
  10. }  
  11.   
  12. static void hello_exit(void)  
  13. {  
  14.         printk(KERN_ALERT "Hello, World! This is exit./n");  
  15. }  
  16.   
  17. module_init(hello_init);  
  18. module_exit(hello_exit);  

二、Makefile

 

  1. obj-m :=hello.o  
  2. KERNELDIR :=/lib/modules/`uname -r`/build  
  3. PWD :=$(shell pwd)  
  4. default:  
  5.         make -C ${KERNELDIR} M=${PWD} modules  
  6. clean:  
  7.         rm -f *.o *.ko *.mod.c *.mod.o modules.*  Module.*  

Makefile解释

obj-m :=hello.o 表示要生成hello模块即hello.ko。若hello.o有两个.c源文件(file1.c, file2.c)生成,则须添加hello-objs :=file1.o file2.o…..

KERNELDIRPWD是两个变量名,表示内核源码目录和当前目录

make -C ${KERNELDIR} M=${PWD} modules  -C指定内核源码目录,M指定模块源码目录

注意:makerm命令前是TAB字符,其余行都是顶格写

 

三、编译

$ make

make -C /lib/modules/`uname -r`/build M=/home/test/test modules

make[1]: Entering directory `/usr/src/linux-2.6.34'

  CC [M]  /home/test/test/hello.o

  Building modules, stage 2.

  MODPOST 1 modules

  CC      /home/test/test/hello.mod.o

  LD [M]  /home/test/test/hello.ko

make[1]: Leaving directory `/usr/src/linux-2.6.34'

 

$ ls

hello.c   hello.mod.c  hello.o   modules.order

hello.ko  hello.mod.o  Makefile  Module.symvers

 

四、加载

hello模块加载到内核

$ su

Password:

# insmod hello.ko

 

若是在终端下,可直接看到输出信息

若是在伪终端下,可通过dmesg -ctail /var/log/messages查看

$ dmesg -c

Hello, World! This is init.

 

查看加载的模块中是否有hello模块

$ lsmod |grep hello

hello                    588  0

 

五、卸载

hello模块从内核中卸载

$ su

Password:

# rmmod hello

$ dmesg -c

Hello, World! This is exit.

 

六、参考

LDD3 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
手把手教你如何编写一个Linux内核模块(超详细~)
Linux驱动程序入门—Hello World - 蓝博芯科
Linux内核模块开发(笔记)
编写简单的Linux2.6内核模块(1)
linux模块编程(一)——加载你的模块
linux设备驱动归纳总结(二):模块的相关基础概念
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服