现在的位置: 首页 > 综合 > 正文

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

2013年12月07日 ⁄ 综合 ⁄ 共 1435字 ⁄ 字号 评论关闭

 

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

 

一、hello.c

 

二、Makefile

 

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

抱歉!评论已关闭.