linux module簡介__linux

來源:互聯網
上載者:User

Linux modules:
簡介:
 linux 2.0版本以後都支援模組化,因為核心中的一部分常駐在記憶體中,(如最常使用的進程,如scheduler等),但是其它的進程只是在需要的時候才被載入。如MS-DOS檔案系統只有當mount此類系統的時候才需要,這種按需載入,就是模組。它能使核心保持較小的體積,雖然可以把所有的東東都放在核心中,這樣的話,我們就不需要模組了,但是這樣通常是有特殊的用途(所有要啟動並執行進程都預Crowdsourced Security Testing道的情況)。
 模組另一個優點是核心可以動態載入、卸載它們(或者自動地由kerneld精靈完成)。

Writing, Installing, and Removing Modules

WRiting Modules:
 除了它們運行在核心空間中之外,模組與其它程式類似。所以,必須定義MODULE並且包含標頭檔module.h以及其它的一些核心標頭檔。模組即可以很簡單也可以很複雜。

一般的模組格式如下:

#define MODULE
#include <linux/module.h>
/*... other required header files... */

/*
 * ... module declarations and functions ...
 */

int
init_module()
{
 /* code kernel will call when installing module */
}

void
cleanup_module()
{
 /* code kernel will call when removing module */
}

使用核心源碼的模組在用gcc編譯時間,必須使用如下的選項:
-I/usr/src/linux/include

注意並不是所有核心中的變數都被匯出供模組使用的,即使代碼中用extern聲明了。在/proc/ksyms檔案或者程式ksyms中顯示了被匯出的符號。現在的linux核心使用使用EXPORT_SYMBOL(x)宏來不僅匯出符號,而且也匯出版本號碼(version number)。如果是使用者自己定義的變數,使用EXPORT_SYMBOL_NOVERS(x)宏。否則的話linker不會在kernel symbol table中保留此變數。可以使用EXPORT_NO_SYMBOLS宏不匯出變數,預設情況是模組匯出所有的變數。

Installing and Removing Modules:
 必須是超級使用者才可以的。使用insmod來安裝一個模組:
  /sbin/insmod module_name
 rmmod命令移除一個已經安裝了的模組,以及任何此模組所匯出的引用。
  /sbin/rmmod module_name
 使用lsmod列出所有安裝了的模組。

Example:
 simple_module.c

/* simple_module.c
 *
 * This program provides an example of how to install a trivial module
 *  into the Linux kernel. All the module does is put a message into
 *  the log file when it is installed and removed.
 *
 */


#define MODULE
#include <linux/module.h>
/* kernel.h contains the printk function */
#include <linux/kernel.h>

/* init_module
 * kernel calls this function when it loads the module
 */
int
init_module()
{
 printk("<1>The simple module installed itself properly./n");
 return 0;
} /* init_module */

/* cleanup_module
 * the kernel calls this function when it removes the module
 */
void
cleanup_moudle()
{
 printk("<1>The simple module is now uninstalled./n");
} /* cleanup_module */

This is the Makefile:

# Makefile for simple_module

CC=gcc -I/usr/src/linux/include/config
CFLAGS=-O2 -D__KERNEL__ -Wall

simple_module.o : simple_module.c

install:
 /sbin/insmod simple_module

remove:
 /sbin/rmmod simple_module

相關文章

聯繫我們

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