linux內核模塊和驅動(dòng)程序的編寫(xiě)
linux中的大部分驅動(dòng)程序,是以模塊的形式編寫(xiě)的.這些驅動(dòng)程序源碼可以修改到內核中,也可以把他們編譯成模塊形勢,在需要的時(shí)候動(dòng)態(tài)加載.
一個(gè)典型的驅動(dòng)程序,大體上可以分為這么幾個(gè)部分:
1、注冊設備
在系統初啟,或者模塊加載時(shí)候,必須將設備登記到相應的設備數組,并返回設備的主驅動(dòng)號,例如:對快設備來(lái)說(shuō)調用refister_blkdec()將設備添加到數組blkdev中.并且獲得該設備號.并利用這些設備號對此數組進(jìn)行索引.對于字符驅動(dòng)設備來(lái)說(shuō),要使用module_register_chrdev()來(lái)獲得祝設備的驅動(dòng)號.然后對這個(gè)設備的所有調用都用這個(gè)設備號來(lái)實(shí)現
2、定義功能函數
對于每一個(gè)驅動(dòng)函數來(lái)說(shuō).都有一些和此設備密切相關(guān)的功能函數.那最常用的塊設備或者字符設備來(lái)說(shuō).都存在著(zhù)諸如 open() read() write() ioctrol()這一類(lèi)的操作.當系統社用這些調用時(shí).將自動(dòng)的使用驅動(dòng)函數中特定的模塊.來(lái)實(shí)現具體的操作.而對于特定的設備.上面的系統調用對應的函數是一定的.
如:在塊驅動(dòng)設備中.當系統試圖讀取這個(gè)設備(即調用read()時(shí)),就會(huì )運行驅動(dòng)程序中的block_read() 這個(gè)函數. 打開(kāi)新設備時(shí)會(huì )調用這個(gè)設備驅動(dòng)程序的device_open() 這個(gè)函數.
3、卸載模塊
在不用這個(gè)設備時(shí),可以將他卸載.主要是從/proc 中取消這個(gè)設備的特殊文件.可用特定的函數實(shí)現.
下面我們列舉一個(gè)字符設備驅動(dòng)程序的框架.來(lái)說(shuō)明這個(gè)過(guò)程.
/* 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
define MODBERSIONS
#include" linux.modversions.h"
#endif
#difine devicename mydevice
/* the init funcion*/
int init_module()
{
int tag=module_register_chrdev(0,mydevice,Fops);
if (tag0)
{
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( re0)
{
printk("erro unregister the module !!n");
return 1;
}
return 0;
}
linux操作系統文章專(zhuān)題:linux操作系統詳解(linux不再難懂)
評論