hello.c

一、hello.c

 

[cpp]  view plain  copy
  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

 

[cpp]  view plain  copy
  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…..

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

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

注意:make和rm命令前是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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值