#include <linux/kernel.h> #include <linux/module.h> static int __init helloworld_init(void) { printk("<0>""helloworld!\n"); return 0; } static void __exit helloworld_exit(void) { printk("<0>""byebye!\n"); } module_init(helloworld_init); module_exit(helloworld_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("haoning");
Makefile
ifneq ($(KERNELRELEASE),) obj-m := helloworld.o else PWD := $(shell pwd) KVER ?= $(shell uname -r) KDIR := /lib/modules/$(KVER)/build all: $(MAKE) -C $(KDIR) M=$(PWD) modules clean: rm -rf *.cmd *.o *.mod.c *.ko *.mod.o *.ko.unsigned modules.order Module.symvers endif
make
[root@mytest kernel]# make make -C /lib/modules/2.6.32-431.11.2.el6.x86_64/build M=/data/haoning/kernel modules make[1]: Entering directory `/usr/src/kernels/2.6.32-431.11.2.el6.x86_64' CC [M] /data/haoning/kernel/helloworld.o Building modules, stage 2. MODPOST 1 modules CC /data/haoning/kernel/helloworld.mod.o LD [M] /data/haoning/kernel/helloworld.ko.unsigned NO SIGN [M] /data/haoning/kernel/helloworld.ko make[1]: Leaving directory `/usr/src/kernels/2.6.32-431.11.2.el6.x86_64' [root@mytest kernel]#
[root@mytest kernel]# ls helloworld.c helloworld.ko helloworld.ko.unsigned helloworld.mod.c helloworld.mod.o helloworld.o Makefile modules.order Module.symvers [root@mytest kernel]# [root@mytest kernel]# insmod helloworld.ko [root@mytest kernel]# Message from syslogd@mytest at Jun 4 19:30:47 ... kernel:helloworld! [root@mytest kernel]# rmmod helloworld.ko Message from syslogd@mytest at Jun 4 19:31:02 ... kernel:byebye! [root@mytest kernel]#
tailf /var/log/messages
查看日志
obj-m 意思是将后面跟的东西编译成内核模块。相对应还有:
obj-y 编译进内核
obj-n 不编译
hello.o 为模块名称
hello.o-objs 为模块依赖的文件名
KID 指定了内核源码的路径
PWD
为当前路径
-C 选项的作用是指将当前工作目录转移到你所指定的位置。
“M=”
选项的作用是,当用户需要以某个内核为基础编译一个外部模块的话,
需要在make modules 命令中加入“M=dir”,程序会自动到你所指定的dir目录中查找模块源码,
将其编译,生成KO文件