Username: Password:

Linux系统内核模块和驱动的编写 (2)
来源:互连网作者:互连网 发布时间:2008-04-07 03:01:39

这样一个例子就完成了.我们也写一个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中的大部分驱动程式,是以模块的形式编写的,这些驱动程式源码能够修改到内核中,也能够把他们编译成模块形势,在需要的时候动态加载。 
  一个典型的驱动程式,大体上能够分为这么几个部分: 
  1.注册设备 
  在系统初启,或模块加载时候,必须将设备登记到相应的设备数组,并返回设备的主驱动号,例如:对快设备来说调用 refister_blkdec() 将设备添加到数组blkdev中,并且获得该设备号,并利用这些设备号对此数组进行索引。对于字符驱动设备来说,要使用  module_register_chrdev()来获得祝设备的驱动号,然后对这个设备的任何调用都用这个设备号来实现。
  2.定义功能函数 
  对于每一个驱动函数来说,都有一些和此设备密切相关的功能函数,那最常用的块设备或字符设备来说,都存在着诸如 open() read()  write() ioctrol()这一类的操作。当系统社用这些调用时,将自动的使用驱动函数中特定的模块,来实现具体的操作。而对于特定的设备,上面的系统调用对应的函数是一定的。
  如:在块驱动设备中.当系统试图读取这个设备(即调用read()时),就会运行驱动程式中的block_read() 这个函数。 
  打开新设备时会调用这个设备驱动程式的device_open() 这个函数. 
3.谢载模块  

  在不用这个设备时,能够将他卸载,主要是从/proc 中取消这个设备的特别文档,可用特定的函数实现。  

下面我们列举一个字符设备驱动程式的框架.来说明这个过程.  

/* 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;  

}   

喜欢本文,那就收藏到:

    Del.icio.us Google书签 Digg Live Bookmark Technorati Furl Yahoo书签 Facebook 百度搜藏 新浪ViVi 365Key网摘 天极网摘 和讯网摘 博拉网 POCO网摘 添加到饭否 QQ书签 Digbuzz我挖网
相关评论  我也要评论
还没有关于此文章的相关评论!
  • 昵称: (为空则显示guest)
  • 评论分数: ★ ★ ★★★ ★★★★ ★★★★★
  • 评论内容:(不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
  • 导航
    赞助商
    文章类别
    订阅