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