1. 在任何目录下,创建一个文件夹 test
2. test 下,创建test.c makefile
test.c
#include <linux/module.h>
#include <linux/init.h> /* to indicate init func and clean func*/
MODULE_LICENSE("GPL");
/* init the module */
static int __init my_initfunc(void) {
/* this is the initialize codes*/
printk( "Hello, zqf \n" );
return 0;
}
/* clean and exit the module */
static void __exit my_cleanupfunc(void){
/* this is the clean and exit codes */
printk( " Goodbye, I am exiting from this module now! \n");
}
module_init(my_initfunc);
module_exit(my_cleanupfunc);
Makefile
# Makefile2.6
ifneq ($(KERNELRELEASE),)
#kbuild syntax. dependency relationshsip of files and target modules are listed here.
mymodule-objs := hello.o
obj-m := hello.o
else
PWD := $(shell pwd)
KVER ?= $(shell uname -r)
KDIR := /lib/modules/$(KVER)/build
all:
$(MAKE) -C $(KDIR) M=$(PWD)
clean:
rm -rf .*.cmd *.o *.mod.c *.ko .tmp_versions
endif
3. 模块编译
在test 目录下
make -C /home/hi/linux-kernel/linux-2.6 M=$PWD
其中,home/hi/linux-kernel/linux-2.6 是kernel的源码路径。
4. 模块装载,卸载和检查
sudo insmod ./hello.ko
sudo rmmod ./hello.ko
lsmod | grep hello 检查内核是不是已经有这个模块了。
shell@NX511J:/ $ lsmod
texfat 149798 0 - Live 0x0000000000000000 (PO)
可以进入sys/module查看具体的模块。
5. log 查询 (http://www.cnblogs.com/QuLory/archive/2012/10/23/2736339.html)
$tail /var/log/kern.log # 注意ubuntu下的日志路径 Oct 23 22:22:22 qunengrong-Studio-1450 kernel: [43021.773888] Hello kernel, it's 2012! Oct 23 22:22:37 qunengrong-Studio-1450 kernel: [43037.092339] Bye, kernel!