写一个模块,必须有一定的多进程编程基础。因为你变得程序不是以一个独立的程序的来运行的。另外,因为,模块需要 在内核模式下运行,会遇到在内和空间和用户空间数据交换的问题。一般的数据复制函数无法完成这一个过程。因此系 统已入了一些特殊的函数以用来完成内核空间和用户空间数据的交换。这些函数有:void put _user (type valude,type *u_addr) memcpy_tofs()等等,有兴趣的朋友可以仔细的看看所有的函数,以及他们的用法。需要说明的是。模块编程河内核的版本有很大的关系。如果版本不通可能造成,内核模块不能编译,或者。在运行这个模块时,出现不可测结果。如:系统崩溃等。
明白了这些以后。你就可以尝试着编写内核模块了。对于每一个内核模块来说。必定包含两个函数 int init_module() 这个函数在插入内核时启动,在内核中注册一定的功能函数,或者用他的代码代替内和中某些函数的内容(估计这些函数是空的)。因此,内和可以安全的卸载。(个人猜测)int cleanup_module() 当内核模块谢载时,调用。将模块从内核中清除。
同其他的程序设计教程一样 ,我们给出一个hello world 的例子:
/*hello.c a module programm*/
/* the program runing under kernel mod and it is a module*/
#include" linux/kernerl.h"
#include"llinux/module.h"
/* pross the CONFIG_MODVERSIONS*/
#if CONFIG_MODVERSIONS==1
#define MODVERSIONS
#include""linux/modversions.h"
#end if
/* the init function*/
int init_module()
{
printk(" hello world !n');
printd(" I have runing in a kerner mod@!!n");
return 1;
}
/* the distory function*/
int cleanup_module()
{
printk(" I will shut down myself in kernerl mod /n)";
retutn 0;
}
# a makefile for a module
CC=gcc
MODCFLAGS:= -Wall _DMODULE -D_KERNEL_ -Dlinux
hello.o hello.c /usr/inculde?linux/version.h
CC $(MODCFLAGS) 0c hello.c
echo the module is complie completely
然后你运行make 命令 得到hello.o 这个模块运行:
$insmod hello.o
hello world!
I will shut down myself in kernerl mod
$lsmod
hello (unused)
…
$remmod
I will shut down myself in kernerl mod
/* a module of a character device */
/* some include files*/
#include"param.h"
#include"user.h"
#include"tty.h"
#include"dir.h"
#include”fs.h"
/* the include files modules need*/
#include"linux/kernel.h"
#include"linux/module.h"
#if CONFIG_MODBERSIONS==1
degine MODBERSIONS
#include" linux.modversions.h"
#endif
#difine devicename mydevice
/* the init funcion*/
int init_module()
{
int tag=module_register_chrdev(0,mydevice,&Fops);
if (tag<0)
{
printk("the device init is erro!n");
return 1;
}
return 0;
}
/*the funcion which the device will be used */
int device_open ()
{
……
}
int device_read ()
{
……
}
int device_write ()
{
……
}
int device_ioctl ()
{
……
}
……
/* the deltter function of this module*/
int cleanup_module()
{
int re=module_unregister_chrdev(tag,mydevice);
if( re<0)
{
printk("erro unregister the module !!n");
return 1;
}
return 0;
}