Linux: 编写一个简单的内核模块

1. 前言

限于作者能力水平,本文可能存在谬误,因此而给读者带来的损失,作者不做任何承诺。

2. 编写模块

2.1 编写模块代码

/*
 * hello_module.c
 */

#include <linux/module.h>


static int __init hello_module_init(void)
{
	printk(KERN_INFO "Hello, module!\n");
	return 0;
}

static void __exit hello_module_exit(void)
{
	printk(KERN_INFO "Bye, module!\n");
}

module_init(hello_module_init);
module_exit(hello_module_exit);

MODULE_LICENSE("GPL");

2.2 编写 Makefile

ifneq ($(KERNELRELEASE),)

obj-m	:= hello_module.o

else

KERNELDIR ?= /lib/modules/$(shell uname -r)/build
PWD       := $(shell pwd)

modules:
	$(MAKE) -C $(KERNELDIR) M=$(PWD) modules

endif

clean:
	rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions .cache.mk modules.order Module.symvers

3. 编译和运行

3.1 编译

bill@bill-virtual-machine:~/Study/host/kernel/module/hello$ make 
make -C /lib/modules/4.15.0-142-generic/build M=/home/bill/Study/host/kernel/module/hello modules
make[1]: Entering directory '/usr/src/linux-headers-4.15.0-142-generic'
  CC [M]  /home/bill/Study/host/kernel/module/hello/hello_module.o
  Building modules, stage 2.
  MODPOST 1 modules
  CC      /home/bill/Study/host/kernel/module/hello/hello_module.mod.o
  LD [M]  /home/bill/Study/host/kernel/module/hello/hello_module.ko
make[1]: Leaving directory '/usr/src/linux-headers-4.15.0-142-generic'

3.2 运行

3.2.1 加载模块

bill@bill-virtual-machine:~/Study/host/kernel/module/hello$ sudo insmod hello_module.ko

bill@bill-virtual-machine:~/Study/host/kernel/module/hello$ dmesg | tail -n 8
[  121.167582] Bluetooth: RFCOMM socket layer initialized
[  121.167588] Bluetooth: RFCOMM ver 1.11
[  265.121990] ISO 9660 Extensions: Microsoft Joliet Level 3
[  265.166143] ISO 9660 Extensions: RRIP_1991A
[17104.215054] hello_module: loading out-of-tree module taints kernel.
[17104.255803] hello_module: module verification failed: signature and/or required key missing - tainting kernel
[17104.270836] Hello, module!

3.2.2 卸载模块

bill@bill-virtual-machine:~/Study/host/kernel/module/hello$ sudo rmmod hello_module

bill@bill-virtual-machine:~/Study/host/kernel/module/hello$ dmesg | tail -n 8
[  121.167582] Bluetooth: RFCOMM socket layer initialized
[  121.167588] Bluetooth: RFCOMM ver 1.11
[  265.121990] ISO 9660 Extensions: Microsoft Joliet Level 3
[  265.166143] ISO 9660 Extensions: RRIP_1991A
[17104.215054] hello_module: loading out-of-tree module taints kernel.
[17104.255803] hello_module: module verification failed: signature and/or required key missing - tainting kernel
[17104.270836] Hello, module!
[17123.218457] Bye, module!
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值