Linux 2.6.xx 核心模組編程入門

來源:互聯網
上載者:User
轉自:http://hi.baidu.com/liu_bin0101/blog/item/02ff1afc043443f5fd037f95.html

2.6.xx 核心與 2.4.XX核心編程有很大不同。下面這些文字簡單說明一下2.6.xx下一個核心模組(Hello World)實現方法。

環境:ubuntu 704
Kernel:     2.6.20-15-generic   , 可以通過 uname -r 查看
gcc版本:     4.1.2


一. 準備工作
安裝kernel 必須的開發庫

#sudo apt-get install linux-kernel-devel

安裝核心標頭檔

#sudo apt-get install linux-headers-`uname -r`

當然, gcc /make 等工具天生就是需要的。


二. 編寫代碼 hello.c

如下:

//------------------hello.c-------------------//


#ifndef __KERNEL__

#define __KERNEL__


#endif

#ifndef MODULE

#define MODULE

#endif


#include <linux/init.h>

#include <linux/module.h>

#include <linux/kernel.h>


static int hello_init(void)

{

         printk(KERN_ALERT "Hello World!/n");

         return 0;

}


static void hello_exit(void)

{

         printk(KERN_ALERT "Bye World!/n");

}


module_init(hello_init);

module_exit(hello_exit);


MODULE_LICENSE("GPL");

MODULE_AUTHOR("WFJ");


//-------------------end of hello.c-------------------//


三. 編寫Makefile 檔案,與hello.c 放在同一個目錄裡

obj-m := hello.o

KERNELBUILD :=/lib/modules/`uname -r`/build

default:

         make -C $(KERNELBUILD) M=$(shell pwd) modules

clean:

         rm -rf *.o *.ko *.mod.c .*.cmd .tmp_versions

(注意makefile裡面要求的tab)

四. 編譯模組


#sudo make

編譯模組

這時,在hello.c 所在檔案夾就會有 hello.ko ,這個就是我們需要的核心模組啦,哈哈!

#sudo make clean

清理編譯垃圾,hello.ko 也會清理掉,呵呵。

四. 插入模組,讓其工作


#sudo insmod ./hello.ko

我們用dmesg 就可以看到 產生的核心資訊啦,Hello world!


#sudo rmmod ./hello

再用dmesg 可以看到 Bye world!

這就是在2.6.xx下一個最簡單的模組編寫過程。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.