Linux modules:
簡介:
linux 2.0版本以後都支持模塊化,因爲內核中的一部分常駐在內存中,(如最常使用的進程,如scheduler等),但是其它的進程只是在需要的時候才被載入。如MS-DOS文件系統只有當mount此類系統的時候才需要,這種按需加載,就是模塊。它能使內核保持較小的體積,雖然可以把所有的東東都放在內核中,這樣的話,我們就不需要模塊了,但是這樣通常是有特殊的用途(所有要運行的進程都預先知道的情況)。
模塊另一個優點是內核可以動態的加載、卸載它們(或者自動地由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