linux 核心模組的編寫,插入,顯示及卸載

來源:互聯網
上載者:User

標籤:檔案   linux   io   file   ui   ubuntu   

環境:ubuntu 8.04

核心版本:2.6.32.59-debug

1、編寫檔案hello.c

#include <linux/init.h>

#include <linux/kernel.h>  //printk

/*寫核心驅動的時候 必須載入這個標頭檔,作用是動態將模組載入到核心中去,常用的宏定義如 MODULE_LICESENCE(),MODULE_AUTHOR(),等在此檔案中*/

#include <linux/module.h>

 

MODULE_LICENSE("Dual BSD/GPL");  //為必須選擇的語句,它是模組的許可許可權,如果不聲明,會出現警告資訊。

 

static int hello_init(void)

{

  printk("Hello, world -- this is the kernel speaking\n");  //printk:與printfde 區別是運行於核心態,且有訊息層級機制 

  return 0;

}

 

static void hello_exit(void)

{

  printk("Short is the life of a kernel module\n");

}

 

module_init(hello_init);  //進入點不再是main( )函數,而應該是module_init( 函數名 )函數

module_exit(hello_exit);  //模組的卸載點指定為hello_exit函數指標

 

2、編寫Makefile

obj-m:=hello.o

KERNELBUILD := /lib/modules/2.6.32.59-debug  //本Makefile 依賴的linux核心源碼路徑  ,如是交叉編譯時間就取開發板上啟動並執行源碼路徑

all:

  make -C $(KERNELBUILD) M=$(shell pwd) modules //到linux源碼所在的目錄執行主Makefile 併當前路徑傳給主Makefile,告訴主Makefile執行完後返回到目前的目錄,執行Makefile

  echo insmod ./hello.ko to turn it on

 

clean:

  rm -rf *.o *.ko *.mod.c *order *.symvers .tmp_versions

 

3、在hello.c目錄下make,於是目前的目錄出現了 hello.ko

4、insmod hello.ko    

5、dmesg -C查看核心資訊(由第四步產生的)

6、lsmod | grep "hello"  命令可以看到hello核心模組,如果第四步正確的話

7、rmmod hello    //刪除核心模組hello.ko

8、dmesg -C查看核心資訊(由第七步產生)。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.