久久ER99热精品一区二区-久久精品99国产精品日本-久久精品免费一区二区三区-久久综合九色综合欧美狠狠

新聞中心

EEPW首頁 > 嵌入式系統 > 設計應用 > linux內核模塊和驅動程序的編寫

linux內核模塊和驅動程序的編寫

作者: 時間:2011-02-27 來源:網絡 收藏

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

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操作系統文章專題:linux操作系統詳解(linux不再難懂)


評論


相關推薦

技術專區

關閉