Linux Device Drivers Hello World 模組範例

 

Hello World 範例模組

#include <linux/init.h>

#include <linux/module.h>

MODULE_LICENSE("Dual BSD/GPL");

static int hello_init(void)

{

        printk(KERN_INFO "Hello, world\n");

        return 0;

}

static void hello_exit(void)

{

        printk(KERN_INFO "Goodbye, cruel world\n");

}

module_init(hello_init);

module_exit(hello_exit);

 

通常都可以在根目錄底下的/usr/src 中找到kernel tree,或是自行到官網去下載與本身使用的系統相符的Kernel Tree,可以透過uname –r 來看kernel 版本號。

helloworld-01.JPG

 

由上圖可以看到Ubuntu8.04現在使用的kernel2.6.24-23-generic

所以我們可以到kernel tree( linux-headers-2.6.24-23-generic )去建立hello world範例模組。

 

helloworld-02.JPG

 

建立Hello 資料夾,並且在hello資料夾中建立Makefilehello.c

Makefile內容如下:

obj-m := hello.o

只需這一行即可。

hello.c只需要依照上面的範例即可。

 

開始編譯:

   make -C /usr/src/linux-headers-2.6.24-23-generic/ M=' /usr/src/linux-headers-2.6.24-23-generic/hello' modules

C 後面的路徑代表 kernel tree的位置

M 後面的路徑代表 Module 位置

 

編譯完成產生如下的檔案,要裝載的驅動只有hello.ko

 

helloworld-03.JPG

 

裝載驅動與卸載驅動:

 

helloworld-04.JPG

 

如果你從一個終端模擬器或者在視窗系統中運行 insmod rmmod, 你不會在你的螢幕上看到任何東西. 訊息會進入其中一個系統日誌檔中,(通常在 /var/log/messages,隨系統而異)

 

因為是使用終端模擬器所以在上圖中看不到任何的訊息,故可以到/var/log/messages中去找尋剛剛裝載與卸載的資訊。

 

cat /var/log/messages

 

helloworld-05.JPG

 

Messages的訊息量很大,但最新的訊息卻是出現在最後,所以用cat就可以看到他最後的訊息是否為我們剛剛裝載與卸載的資訊。

 

 

 

 

arrow
arrow
    全站熱搜

    flykof 發表在 痞客邦 留言(4) 人氣()