如何编写一个简单的驱动模块,我们这里可以使用vim编辑一个hello_world.c文件。
#include <linux/module.h>
//模块装载时初始化函数
static int __init hello_init(void)
{
printk("this is a hello world module\n");
return 0;
}
//模块卸载时清理函数
static void __exit hello_exit(void)
{
return;
}
module_init(hello_init);
module_exit(hello_exit);
//作者信息
MODULE_AUTHOR("Hello");
//模块使用的协议类型
MODULE_LICENSE("GPL");
//模块描述信息
MODULE_DESCRIPTION("hello world test");
linux驱动模块的编译工具是make,因此我们需要写一个简单的makefile
ifneq (${KERNELVERSION},)
obj-m := hello.o
hello-objs := hello_world.o
else
KERNEL_VERSION = $(shell uname -r)
KERNEL_BUILD = /lib/modules/${KERNEL_VERSION}/build/
MODULE_DIR = $(shell pwd)
default:
make -C ${KERNEL_BUILD} M=${MODULE_DIR} modules
clean:
make -C ${KERNEL_BUILD} M=${MODULE_DIR} clean
endif
此处的KERNEL_BUILD可以指向源代码目录,也可以通过安装kernel devel开发包的方式指向内核开发包。
该makefile会调用两次,第一次没有定义KERNELVERSION,因此执行的是else部分,进入内核源码执行makefile,内核源码中的makefile里面定义了KERNELVERSION。因此第二次执行该makefile时会执行ifneq部分。