新建一个文件hello.c,编写如下代码:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
MODULE_LICENSE("Dual BSD/GPL");
static int hello_init(void)
{
printk(KERN_ALERT"Hello!\n");
return 0;
}
static void hello_exit(void)
{
printk(KERN_ALERT"Goodbye!\n");
}
module_init(hello_init);
module_exit(hello_exit);
新建一个Makefile文件,编写以下内容:
KERN_DIR = /lib/modules/$(shell uname -r)/build
all:
make -C $(KERN_DIR) M=`pwd` modules
clean:
make -C $(KERN_DIR) M=$(shell pwd) modules clean
rm -rf modules.order
obj-m := hello.o
然后在终端输入:
$ make (即可在目录下看到生成的驱动模块hello.ko文件)
$ sudo insmod hello.ko (将模块加载入内核)
$ sudo rmmod hello (移除指定的内核模块)
本驱动在x86 上测试的, printk 打印出来的信息会在日志文件里。
因此,想查看printk打印的内容,还需要输入:
$ dmesg
结果:
[30664.513378] Goodbye!
[306