一、Makefile
在发行版下编译并运行内核模块是不需要交叉编译的,比如centos、ubuntu,无论当前是X86或者ARM架构,直接使用默认gcc即可,Makefile可有如下模板:
obj-m :=demo.o
all:
make -C /lib/modules/$(shell uname -r)/build SUBDIRS=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build SUBDIRS=$(PWD) clean
二、demo内核模块
内核模块必备的操作函数为:入口函数和出口函数,内核提供了固定的指定入口函数/出口函数的宏,即module_init/module_exit,只要实现这两个函数,即可完成了一个最简单的内核模块编程,有如下代码:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
static int __init demo_init(void)
{
printk("demo init!\n");
return 0;
}
static void __exit demo_exit(void)
{
printk("demo exit!\n");
}
module_init(demo_init);
module_exit(demo_exit);
MODULE_LICENSE("GPL");
三、编译
[root@jingdomain demo]# make
make -C /lib/modules/4.18.0-348.2.1.el8_5.x86_64/build SUBDIRS=/root/temp/kernel_mod/demo modules
make[1]: Entering directory '/usr/src/kernels/4.18.0-348.2.1.el8_5.x86_64'
CC [M] /root/temp/kernel_mod/demo/demo.o
Building modules, stage 2.
MODPOST 1 modules
CC /root/temp/kernel_mod/demo/demo.mod.o
LD [M] /root/temp/kernel_mod/demo/demo.ko
make[1]: Leaving directory '/usr/src/kernels/4.18.0-348.2.1.el8_5.x86_64'
通过make,最终执行生成demo.ko,这个ko模块就是我们将要运行的内核模块。
四、运行
通过insmod命令将编译得到的demo.ko,加载到内核系统中
[root@jingdomain demo]# insmod demo.ko
[root@jingdomain demo]# dmesg | tail -n 3
[469864.922449] demo: loading out-of-tree module taints kernel.
[469864.923609] demo: module verification failed: signature and/or required key missing - tainting kernel
[469864.925694] demo init!
当我们执行insmod的时候,内核会自动加载执行module_init传入的入口函数,demo模块仅仅是一条输出提示,仅仅会打印demo init!
如果我们想将这个内核模块卸载掉,我们可以用rmmod进行卸载
[root@jingdomain demo]# rmmod demo
[root@jingdomain demo]# dmesg | tail -n 1
[470029.429127] demo exit!
[root@jingdomain demo]#
rmmod执行的过程中,会加载内核模块的module_exit传入的出口函数,以回收此模块的资源,本模块仅仅是打印了demo exit!