-
查看内核的版本:
[server hello]$>uname -r
5.0.0-37-generic -
下载对应版本的源码:
sudo apt-get install linux-headers-5.0.0-37-generic
-
编写kernel_hello.c
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
static __init int hello_init(void)
{
printk(KERN_ALERT "Hello Kernel Module OK!\r\n");
return 0;
}
static __exit void hello_exit(void)
{
printk(KERN_ALERT "Goodbye Hello Module\r\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_AUTHOR("xxx");
MODULE_DESCRIPTION("Linux hello module");
MODULE_LICENSE("Dual BSD/GPL");
- 编写Makefile
KERNAL_DIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
obj-m:=kernel_hello.o
modules:
$(MAKE) -C $(KERNAL_DIR) M=$(PWD) modules
@make clear
clear:
@rm -f *.o *.cmd *.mod.c
@rm -rf *~ core .depend .tmp_versions Module.symvers modules.order -f
@rm -f .*ko.cmd .*.o.cmd .*.o.depend
@rm -f *.unsigned
clean:
@rm -f hello.ko
-
查看运行结果
命令行打开dmesg实时打印
dmesg -w
打开一个新的命令行窗口输入:
sudo insmod kernel_hello.ko
sudo rmmod kernel_hello
运行结果在dmesg显示如下:
[11995.800531] Hello Kernel Module OK!
[12112.710453] Goodbye Hello Module