同其他的程序设计教程一样 ,我们给出一个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;
}
这样一个例子就完成了。我们也写一个makefile 的例子,以适于我们在大程序重的应用。一下是makfile 文件的内容:
# 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
这样你的模块就可以随意的插入和删除了。linux中的大部分驱动程序,是以模块的形式编写的。这些驱动程序源码可以修改到内核中,也可以把他们编译成模块形势,在需要的时候动态加载。