下面的代码是一个完整的 "hello world"模块:
然后是makefile 注意2.6的内核只能用makefile编译模块#include <linux/init.h> #include <linux/module.h> MODULE_LICENSE("Dual BSD/GPL"); static int hello_init(void) { printk(KERN_ALERT "Hello, world\n"); return 0; } static void hello_exit(void) { printk(KERN_ALERT "Goodbye, cruel world\n"); } module_init(hello_init); module_exit(hello_exit);
1 # If KERNELRELEASE is defined, we've been invoked from the 2 # kernel build system and can use its language. 3 ifneq ($(KERNELRELEASE),) 4 5 obj-m := hello.o 6 # Otherwise we were called directly from the command 7 # line; invoke the kernel build system. 8 else 9 KERNELDIR ?= /lib/modules/$(shell uname -r)/build 10 PWD := $(shell pwd) 11 default: 12 $(MAKE) -C $(KERNELDIR) M=$(PWD) modules 13 14 endif
操作:
make
可以看到产生了
hello.c hello.ko hello.mod.c hello.mod.o hello.o Makefile modules.order Module.symvers
加载:
cb@ubuntu:~/Desktop/MyProject/LinuxDriver$ sudo insmod ./hello.ko 移除:
cb@ubuntu:~/Desktop/MyProject/LinuxDriver$ sudo rmmod hello
查看日志:
cb@ubuntu:~/Desktop/MyProject/LinuxDriver$ tail -2 /var/log/kern.log
Jul 18 10:52:20 ubuntu kernel: [13235.917043] Hello, world Jul 18 10:52:25 ubuntu kernel: [13241.282165] Goodbye, cruel world