前言#
正好今天开始开始看《Linux内核设计与实现》这本书,就以Hello,world开个头吧
实现#
// 模块所需头文件
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/moduleparam.h>
// 许可证书
MODULE_LICENSE("GPL");
static int __init mod_init(void) {
printk(KERN_ALERT "Hello, World\n");
return 0;
}
static void __exit mod_exit(void) {
printk(KERN_ALERT "Goodbye\n");
}
module_init(mod_init);
module_exit(mod_exit);
obj-m := hello.o
CURRENT_PATH := $(shell pwd)
VERSION_NUM := $(shell uname -r)
LINUX_PATH := /usr/src/linux-headers-$(VERSION_NUM)
all:
make -C $(LINUX_PATH) M=$(CURRENT_PATH) modules
clean:
make -C $(LINUX_PATH) M=$(CURRENT_PATH) clean
这里可以看到的是内核模块的输出与标准输出有稍许不同的地方:
printk
中KERN_*
代表了优先级,与输出内容隔一个空格printf
就是标准输出,只是调用系统函数输出字符串
运行#
直接make得到一大串文件
.
├── Makefile
├── Module.symvers
├── hello.c
├── hello.ko
├── hello.mod.c
├── hello.mod.o
├── hello.o
└── modules.order
这里输出的.o文件并不能直接运行,为REL类型
*.ko
即为我们所需的内核模块,insmod ${name}.ko
将模块加载进内核
用dmesg查看输出
[46478.783149] WSL2: Performing memory compaction.
[46539.789768] WSL2: Performing memory compaction.
[46660.796831] WSL2: Performing memory compaction.
[46781.803469] WSL2: Performing memory compaction.
[46902.810284] WSL2: Performing memory compaction.
[46963.817192] WSL2: Performing memory compaction.
[47007.007476] Hello, World
然后rmmod $(name)
退出该模块
[53723.654584] WSL2: Performing memory compaction.
[53784.665033] WSL2: Performing memory compaction.
[53845.672471] WSL2: Performing memory compaction.
[53906.679157] WSL2: Performing memory compaction.
[54027.685937] WSL2: Performing memory compaction.
[54054.799471] Goodbye