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!
posted @ 2025-04-07 14:45  JiMoKuangXiangQu  阅读(26)  评论(0)    收藏  举报