内核模块编程包括以下几部分:
编写模块代码;
编写Makefile文件;
用make命令编译模块文件;
用insmod命令将模块插入内核;
用dmesg命令查看输出;
用rmmod命令卸载模块。
我在 /home/shana/linux_q/ 目录下创建2个文本文件 hello.c 和 Makefile
//hello.c
#include <linux/init.h>
#include <linux/module.h>
MODULE_LICENSE("Dual BSD/GPL");
/*
模块加载函数,在使用insmod命令加载模块时,模块的加载函数会自动被内核执行,完成模块的相关初始化工作,通常包括:(1)向内核注册一些数据结构;(2)申请软硬件资源;(3)初始化硬件。
*/static int hello_init(void)
{
printk(KERN_ALERT "Hello, world\n");
return 0;
}
/*
模块卸载函数,使用rmmod命令卸载模块时,模块的卸载函数会自动被内核执行,完成与模块装载函数相反的功能(注销一些内核数据结构,释放资源等)。
*/static void hello_exit(void)
{
printk(KERN_ALERT"Goodbye, cruel world\n");
}
/*
模块加载函数和模块卸载函数必须用宏“module_init”和module_exit指定。
*/module_init(hello_init);
module_exit(hello_exit);
Makefile 文件:
KERNELDIR := /lib/modules/2.6.20/build
PWD := $(shell pwd)
modules:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
modules_install:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install
如果以上你都完成了在 make 时出现这样的错误 :
MODPOST 0 modules
原因很简单,Makefile格式错误啦~解决办法就是 你把如 $(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install 移动到行首 然后按Tab 键自动对齐
,然后 make 吧
shana@shana:~/linux_驱动开发$ make
make -C /lib/modules/2.6.22-14-generic/build M=/home/shana/linux_驱动开发 modules
make[1]: Entering directory `/usr/src/linux-headers-2.6.22-14-generic'
CC [M] /home/shana/linux_驱动开发/hello.o
Building modules, stage 2.
MODPOST 1 modules
CC /home/shana/linux_驱动开发/hello.mod.o
LD [M] /home/shana/linux_驱动开发/hello.ko
make[1]: Leaving directory `/usr/src/linux-headers-2.6.22-14-generic'
shana@shana:~/linux_驱动开发$
查看编译后生成的文件:
shana@shana:~/linux_驱动开发$ ls -l
总用量 124
-rw-r--r-- 1 shana shana 303 2008-03-16 10:43 hello.c
-rw-r--r-- 1 shana shana 49039 2008-03-16 12:11 hello.ko
-rw-r--r-- 1 shana shana 687 2008-03-16 12:11 hello.mod.c
-rw-r--r-- 1 shana shana 25840 2008-03-16 12:11 hello.mod.o
-rw-r--r-- 1 shana shana 24360 2008-03-16 12:11 hello.o
-rw-r--r-- 1 shana shana 8344 2008-03-16 09:17 linux_qudong_qu.txt
-rw-r--r-- 1 shana shana 266 2008-03-16 12:09 Makefile
-rw-r--r-- 1 shana shana 0 2008-03-16 12:11 Module.symvers
shana@shana:~/linux_驱动开发$
然后加载模块 (超级用户)
root@shana:/home/shana/linux_驱动开发# insmod ./hello.ko
root@shana:/home/shana/linux_驱动开发#
查看加载模块
root@shana:/home/shana/linux_驱动开发# lsmod
Module Size Used by
hello 2560 0
已经加载上咯~~
root@shana:/home/shana/linux_驱动开发# dmesg
这里会显示模块加载函数里的打印语句
删除模块
root@shana:/home/shana/linux_驱动开发# rmmod hello
root@shana:/home/shana/linux_驱动开发#
root@shana:/home/shana/linux_驱动开发# dmesg
这里会显示模块卸载函数里的打印语句