开发准备
安装Linux 源码
apt install komd linux-headers-`uname -r`-generic
编写待编译的代码 hello.c (非最简单版本)
#include <linux/init.h> // 预编译的宏
#include <linux/module.h> // 必须包含的文件
#include <linux/printk.h> // 输出打印类函数
MODULE_LICENSE("GPL");
MODULE_AUTHOR("SECBUG");
MODULE_DESCIPTION("This is a driver");
static int hello_data __initdata = 3;
static int __init hello_init(void) {
pr_info("hello world %d\\n", hello_data);
return 0;
}
static void __exit hello_cleanup(void) {
pr_info("Goodbye world\\n");
}
module_init(hello_init);
module_exit(hello_cleanup);
编译
编写Makefile文件
obj-m += hello.o
PWD=$(CURDIR)
all:
make -C /lib/modules/$(shell name -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell name -r)/build M=$(PWD) clean
安装与移除
insmod 安装驱动文件
insmod hello.ko
rmmod 移除驱动文件
rmmod hello
lsmod 列出当前所有驱动文件
journalctl 日志查询
journalctl --since "1 hour ago" | grep kernel