模块是Linux驱动加载,卸载的基本单位。下面描述如何建立一个基本模块。
首先,建立一个目录作为自己的工作目录,比如我的是~/kernel/mymodule。然后,新建一个hello.c文件,代码如下:
#include <linux/module.h>
MODULE_LICENSE("Dual BSP/GPL");
static int hello_init(void)
{
printk(KERN_ALERT "Hello,world.\n");
return 0;
}
static int hello_exit(void)
{
printk(KERN_ALERT "Goodbye, cruel world.\n");
return 0;
}
module_init(hello_init);
module_exit(hello_exit);
再建立一个Makefile文件,注意文件名字是“Makefile”,不能是“makefile”或其它名字。文件内容如下:
# kernel build system and can use its language
ifneq ($(KERNELRELEASE),)
obj-m := hello.o
# Otherwise we were called directly from the command
# line; invoke the kernel build system
else
KERNELDIR := /usr/src/linux-headers-3.2.0-23-generic-pae/
PWD := $(shell pwd)
default:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
endif
然后,直接在命令行敲入make就可以编译了。
编译成功后,使用sudo insmod ./hello.ko安装,lsmod查看已经安装的模块,rmmod hello卸载模块。
很多书上说要先下载源码才能编译模块,但我的测试是不用。当然,下载源码编译学习对驱动开发来说也是很重要的。