Linux下開始乙個簡單核心模組 hello

2021-06-14 08:41:02 字數 1534 閱讀 1467

目的:建立乙個簡單的核心模組,並把它掛載到核心中去。這個核心模組沒有與外界有任何的資料互動。

//定義__kernel__表示此原始檔可以看到核心原始檔的所有內容

//因為有的核心的標頭檔案會被使用者空間的應用程式包含,但是內

//核中的內容有些是核心專用的,需要對使用者隱藏起來

#ifndef __kernel__

#define __kernel__

#endif

//如果要把**編譯成乙個核心模組,必須定義它

#ifndef module

#define module

#endif

#include

#include

#include

//一些模組說明巨集,這裡沒有全部列出

module_license("gpl");

module_description("a ****** hello module");

module_author("kcb");

static int year = 2013;

static int __init hello_init(void)

static void __exit hello_exit(void)

//module_init, module_exit是巨集,他們分別表示模組載入和解除安裝時的

//執行函式,如hello_init, hello_exit.

//當我們注釋掉這兩個巨集的時候,編譯時會發出警告,這兩個函式被定義了

//但是沒有被使用: warning: 'hello_init' defined but not used

module_init(hello_init);

module_exit(hello_exit);

//makefile

obj-m := hello.o

all:

$(make) -c /lib/modules/$(shell uname -r)/build m=$(pwd) modules

clean:

$(make) -c /lib/modules/$(shell uname -r)/build m=$(pwd) clean

本人的機器環境是虛擬機器中ubuntu11.10

在檔案儲存的路徑下執行make

$make

將模組掛載到核心中去

$sudo insmod hello.ko

我們檢查系統中是否掛載了我們的模組,前面提到過當模組掛載時,我們的hello.c中被執行的函式hello_init,這個函式的功能就是

列印hello kernel, it's 2013, 我們現在檢查是否列印了這條語句

$dmesg | tail

最後一條訊息告訴我們我們的hello模組掛載到了核心中。

解除安裝模組hello

$sudo rmmod hello

$dmesg | tail

bye, kernel!

最後,作者對上述的makefile檔案還是不夠熟悉,沒有對其進行注釋,希望了解的人可以給個鏈結,共同學習。

Linux環境下最簡單核心模組的實踐

1.最簡單驅動原始檔 include include module license dual bsd gpl static int hello init void static void hello exit void module init hello init module exit hello...

乙個簡單的linux核心驅動

一,核心結構簡單概述 上層程式操作裝置驅動簡單概述 在使用者空間使用相關的c庫,比如open函式會造成乙個中斷,系統會去呼叫sys call函式 系統呼叫 然後會去呼叫相關的sys open函式,在核心空間的時候會去驅動鏈表裡面查詢對應的外設驅動,我們編寫完驅動程式,載入到核心,核心會去呼叫相關的驅...

開始寫乙個核心模組

從hello world開始,乙個完整的核心模組helloword.c如下 include module init 和 module exit 的標頭檔案 include 這個標頭檔案包含了許多符號與函式的定義,這些符號與函式多與載入模組有關 module license dual bsd gpl ...