今年打算好好學一下 Linux 內核開發。萬事開頭難,第一步自然是編譯內核,試了很多次都以失敗告終,昨天終於第一次在虛擬機上成功升級內核,今天就來寫個 hello world 模塊試試——它和寫普通 Linux 應用程式的差別還真不小。
#include <linux/module.h>
#include <linux/init.h>
int __init hello_init (void)
{
printk("HelloWorld\n");
return 0;
}
void __exit hello_exit(void)
{
printk("GoodBye\n");
}
MODULE_AUTHOR("wanghaifeng <haifengwang1987@gmail.com>");
MODULE_DESCRIPTION("hello");
MODULE_LICENSE("GPL");
module_init(hello_init);
module_exit(hello_exit);
這段代碼沒有 main 函數,編譯方式也不能用 gcc 的常規寫法。模塊透過 module_init() 與 module_exit() 向內核註冊,每個模塊都必須有初始化與退出函數。
新建一個 Makefile,內容只有一行:
obj-m :=hello.o
我的編譯環境是 RedHat 5.3,內核版本 2.6.18-53.el5,執行:
# make -C /usr/src/kernels/2.6.18-53.el5-i686/ modules M=$PWD
看到目錄裡多出幾個文件,hello.ko 就是生成的內核模塊:
# ls
hello.c hello.ko hello.mod.c hello.mod.o hello.o Makefile Module.symvers
用 insmod、lsmod、rmmod 分別完成這三件事,printk 輸出的訊息會寫進 /var/log/messages:
# insmod hello.ko //插入模塊,呼叫 hello_init()
# lsmod | grep -e hello -e Module //查看模塊
# rmmod hello //刪除模塊,呼叫 hello_exit()
# tail -f /var/log/messages //查看日誌
-C 參數指定內核源碼目錄、M 指定模塊所在路徑,這是編寫外部模塊的固定套路,記住它就省下不少摸索。