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