? [cpp]?view plain?copy?print?
//??
//hello.c??
//??
#include???
#include???
#include???
static?int?hello_init(void)?{??
printk(KERN_WARNING?"Module?init:?Hello?world! ");??
return?0;??
}??
static?void?hello_exit(void)?{??
printk(KERN_WARNING?"Module?exit:?bye-bye ");??
}??
module_init(hello_init);??
module_exit(hello_exit);??
最后兩行指定了模塊加載和卸載時(shí)執(zhí)行的函數(shù),加載時(shí)執(zhí)行hello_init,卸載時(shí)執(zhí)行hello_exit。
下面是Makefile文件
[plain]?view plain?copy?print?
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指向了系統(tǒng)當(dāng)前內(nèi)核的源代碼樹(shù)(build是源代碼目錄的一個(gè)鏈接,源代碼一般在/usr/src/kernels/下面)。
之前我有更新系統(tǒng),把我的源代碼給刪掉了,致使build是個(gè)無(wú)效的鏈接,導(dǎo)致編譯不通過(guò),后來(lái)我把
對(duì)應(yīng)版本的源代碼裝上,并給其創(chuàng)建一個(gè)build鏈接復(fù)制到KDIR目錄下覆蓋無(wú)效的那個(gè)鏈接,編譯就成功。
可通過(guò)以下命令安裝源代碼樹(shù):
[root@localhost?~]#?uname?-r??
3.1.0-7.fc16.i686.PAE
查詢當(dāng)前系統(tǒng)的內(nèi)核版本
[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
先查詢相關(guān)的內(nèi)核包。沒(méi)有當(dāng)前內(nèi)核版本的源代碼包和開(kāi)發(fā)包。
參照上面的格式把它安裝上。
[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目錄下會(huì)有相應(yīng)版本的源代碼。
?
條件都具備了就可以編譯模塊了。在hello.c文件目錄下執(zhí)行make命令就會(huì)調(diào)用Makefile來(lái)編譯。
編譯好后,會(huì)生成一個(gè)內(nèi)核模塊hello.ko。這就是我們編譯好的內(nèi)核模塊,接下來(lái)加載它,并查看結(jié)果。
[root@localhost?demo]#?insmod?hello.ko??
[root@localhost?demo]#?dmesg?|?tail?-n?5??
[?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!??
最后一條消息就是我們編寫(xiě)的模塊的輸出。
?
評(píng)論