今天把linux裝置驅動程式(第三版)的第一個模組hello模組編譯通過了,這個東西卡了我好長時間了,期間我又花了很多時間去看linux程式設計(第二版 ),終於今天機械性地完成了這個實驗。
編譯環境:虛擬機器linux2.6.18核心,(如果核心不是2.6的,可以參考我的核心升級過程,另外一篇文章有詳細記錄)
來源程式hello.c:
////////////////////////////////////////////////////////////////////////////
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
MODULE_LICENSE("Dual BSD/GPL");
static int hello_init(void) //有的上面定義的是init_modules(void)是通不過編譯的
{
printk(KERN_ALERT "Hello, world/n");
return 0;
}
static void hello_exit(void)
{
printk(KERN_ALERT "Goodbye, world/n");
}
module_init(hello_init);
module_exit(hello_exit);
////////////////////////////////////////////////////////////////////////
Makefile的內容:
ifneq ($(KERNELRELEASE),)
obj-m := hello.o
else
KDIR:=/lib/modules/$(shell uname -r)/build
PWD:=$(shell pwd)
all:
$(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules
endif
clean:
rm -f *.o *.ko *.mod.c .hello*
//////////////////////////////////////////////////////////
把hello.c Makefile放到同一個文夾hello中,在hello目錄下(我的為/home/leo/hello)編譯時間會提示hellomodules檔案夾找不到,建立hellomodules檔案夾(home/leo/hellomodules)後,再在hello目錄下(home/leo/hello)編譯會提示hello.c Makefile找不到,把hello.c Makefile複製到hellomodules目錄下去,然後編譯就ok了。
載入模組:
insmod ./hello.ko
(系統提示:insmod命令找不到)
linux虛擬機器下有很多命令因為PATH的原因無法找到,我們可以用whereis command 來尋找,這裡用
whereis insmod
(找insmod位置)
(比如說在/usr/***/insmod那麼就用:)
/usr/***/insmod ./hello.ko
(同樣改變系統路徑PATH也可以辦到)
載入後用lsmod 命令查看,可以看到hello模組已經載入到核心中去了,rmmod 命令用法相同。(注意是rmmod hello,不是hello.ko)要看輸出的資訊,我們可以用: demsg | tail -n1 可以看到輸出的“hello world ”和 bye
資訊。