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

本文介绍了一个简单的Linux模块示例,包括源代码、Makefile配置、编译过程、模块的加载与卸载步骤。通过此示例,读者可以了解如何创建并使用基本的Linux内核模块。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

转载请注明出处:http://blog.youkuaiyun.com/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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值