1.0 操作系统环境:
[lg@lg hello]$ uname -a
Linux lg 3.10.0-957.el7.x86_64 #1 SMP Thu Nov 8 23:39:32 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
2.0 编译器版本
gcc version 7.3.1 20180303 (Red Hat 7.3.1-5) (GCC)
3.0 编辑器版本
VIM - Vi IMproved 7.4 (2013 Aug 10, compiled Oct 30 2018 19:56:57)
4.0 示例代码 hello.c
1 #include <linux/init.h>
2 #include <linux/sched.h>
3 #include <linux/module.h>
4
5 MODULE_LICENSE("GPL");
6 MODULE_AUTHOR("lg");
7 MODULE_DESCRIPTION("This is just a hello module!\n");
8
9 static int __init hello_init(void)
10 {
11 printk(KERN_EMERG"hello, init\n");
12 return 0;
13 }
14
15 static void __exit hello_exit(void)
16 {
17 printk(KERN_EMERG"hello, exit\n");
18 }
19
20 module_init(hello_init);
21 module_exit(hello_exit);
5.0 编译脚本 Makefile
1 ifneq ($(KERNELRELEASE),)
2 obj-m := hello.o
3
4 else
5 PWD := $(shell pwd)
6 KVER := $(shell uname -r)
7 KDIR := /lib/modules/$(KVER)/build
8 all:
9 $(MAKE) -C $(KDIR) M=$(PWD) modules
10 clean:
11 rm -rf .*.cmd *.o *.mod.c *.ko .tmp_versions
12 endif
6.0 编译方法
保证hello.c和Makefile在同一目录内,执行执行make即可完成编译
7.0 驱动程序的安装
insmod hello.ko // 加载驱动文件
lsmod | grep hello // 查看驱动文件是否已安装
rmmod hello // 卸载驱动文件
dmesg | tail // 查看加载、卸载驱动文件过程中的打印值.