1. 查看内核版本
[root@localhost test]# uname -r
3.10.0-862.el7.x86_64
2. 切换到相应的内核源码中
[root@localhost test]# cd /usr/src/kernels/3.10.0-862.el7.x86_64/drivers/
[root@localhost test]# mkdir test
3. 编写hello.c 及 Makefile
cat hello.c:
[root@localhost test]# cat hello.c
#include <linux/init.h>
#include <linux/module.h>
MODULE_LICENSE("Dual BSD/GPL");
static int hello_init(void)
{
printk(KERN_ALERT "hello world enter\n");
return 0;
}
static void hello_exit(void)
{
printk(KERN_ALERT "hello world exit\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_AUTHOR("ZHANGNA");
MODULE_DESCRIPTION("A simple Hello world module");
MODULE_ALIAS("A simplest module");
cat Makefile:
[root@localhost test]# cat Makefile
obj-m := hello.o
4. make编译
[root@localhost test]# make -C /usr/src/kernels/3.10.0-862.el7.x86_64/ M=$(pwd) modules
5.查看是否生成hello.ko
modinfo hello.ko将看到该模块的信息
insmod hello.ko,将驱动模块加载到内核中
cat /var/log/messages | tail
将在屏幕上看到系统打印的信息:Feb 17 16:55:19 localhost kernel: hello world enter.
rmmod hello.ko 从内核中移除hello驱动模块和 cat /var/log/messages |tail
将在屏幕上看到系统打印信息:Feb 17 17:12:09 localhost kernel: hello world exit
或者
[root@localhost test]# dmesg | tail
[12104.524237] e1000: ens33 NIC Link is Down
[12110.538934] e1000: ens33 NIC Link is Up 1000 Mbps Full Duplex, Flow Control: None
[13928.048286] e1000: ens33 NIC Link is Down
[13934.079297] e1000: ens33 NIC Link is Up 1000 Mbps Full Duplex, Flow Control: None
[13940.078325] e1000: ens33 NIC Link is Down
[13944.073424] e1000: ens33 NIC Link is Up 1000 Mbps Full Duplex, Flow Control: None
[18396.430433] hello: loading out-of-tree module taints kernel.
[18396.431571] hello: module verification failed: signature and/or required key missing - tainting kernel
[18396.435536] hello world enter
[19403.541193] hello world exit