最近由于學習需要,學習了一下Linux內核模塊的編寫方法,特此把學習過程中的問題記錄下來!!!
- //
- //hello.c
- //
- #include <linux/init.h>
- #include <linux/kernel.h>
- #include <linux/module.h>
-
- static int hello_init(void) {
- printk(KERN_WARNING "Module init: Hello world!\n");
- return 0;
- }
-
- static void hello_exit(void) {
- printk(KERN_WARNING "Module exit: bye-bye\n");
- }
-
- module_init(hello_init);
- module_exit(hello_exit);
最后兩行指定了模塊加載和卸載時執行的函數,加載時執行hello_init,卸載時執行hello_exit。
下面是Makefile文件
- ifneq ($(KERNELRELEASE),)
- obj-m:=hello.o
- else
- KDIR := /lib/modules/$(shell uname -r)/build
-
-
- all:
- make -C $(KDIR) M=$(PWD) modules
- clean:
- make -C $(KDIR) M=$(PWD) clean
- endif
KDIR指向了系統當前內核的源代碼樹(build是源代碼目錄的一個鏈接,源代碼一般在/usr/src/kernels/下面)。
之前我有更新系統,把我的源代碼給刪掉了,致使build是個無效的鏈接,導致編譯不通過,后來我把
對應版本的源代碼裝上,并給其創建一個build鏈接復制到KDIR目錄下覆蓋無效的那個鏈接,編譯就成功。
可通過以下命令安裝源代碼樹:
- [root@localhost ~]# uname -r
3.1.0-7.fc16.i686.PAE 查詢當前系統的內核版本
- [root@localhost ~]# rpm -qa | grep kernel*
kernel-PAE-devel-3.3.0-4.fc16.i686
kernel-PAE-3.3.0-4.fc16.i686
kernel-headers-3.3.0-4.fc16.i686
libreport-plugin-kerneloops-2.0.8-4.fc16.i686
abrt-addon-kerneloops-2.0.7-2.fc16.i686
kernel-devel-3.3.0-4.fc16.i686
先查詢相關的內核包。沒有當前內核版本的源代碼包和開發包。
參照上面的格式把它安裝上。
- [root@localhost ~]# yum install kernel-PAE-devel-3.1.0-7.fc16.i686
- [root@localhost ~]# yum install kernel-PAE-3.1.0-7.fc16.i686
安裝好后,/usr/src/kernels目錄下會有相應版本的源代碼。
條件都具備了就可以編譯模塊了。在hello.c文件目錄下執行make命令就會調用Makefile來編譯。
編譯好后,會生成一個內核模塊hello.ko。這就是我們編譯好的內核模塊,接下來加載它,并查看結果。
- [root@localhost demo]# insmod hello.ko
- [root@localhost demo]# dmesg | tail -n 5
- <span>[ 2445.017321] virbr0: port 2(vif1.0) entering forwarding state
-
- [ 2445.017439] virbr0: port 2(vif1.0) entering disabled state
-
- [ 2494.639683] hello: module license 'unspecified' taints kernel.
-
- [ 2494.639688] Disabling lock debugging due to kernel taint
-
- [ 2494.639841] Module init: Hello world!
- </span>
最后一條消息就是我們編寫的模塊的輸出。