新聞中心

EEPW首頁 > 嵌入式系統(tǒng) > 設(shè)計(jì)應(yīng)用 > 嵌入式Linux設(shè)備驅(qū)動開發(fā)之:字符設(shè)備驅(qū)動編程

嵌入式Linux設(shè)備驅(qū)動開發(fā)之:字符設(shè)備驅(qū)動編程

作者: 時(shí)間:2013-09-13 來源:網(wǎng)絡(luò) 收藏

本文引用地址:http://m.butianyuan.cn/article/257111.htm

11.2字符編程

1.字符編寫流程

程序可以使用模塊的方式動態(tài)加載到內(nèi)核中去。加載模塊的方式與以往的應(yīng)用程序開發(fā)有很大的不同。以往在開發(fā)應(yīng)用程序時(shí)都有一個(gè)main()函數(shù)作為程序的入口點(diǎn),而在驅(qū)動開發(fā)時(shí)卻沒有main()函數(shù),模塊在調(diào)用insmod命令時(shí)被加載,此時(shí)的入口點(diǎn)是init_module()函數(shù),通常在該函數(shù)中完成設(shè)備的注冊。同樣,模塊在調(diào)用rmmod命令時(shí)被卸載,此時(shí)的入口點(diǎn)是cleanup_module()函數(shù),在該函數(shù)中完成設(shè)備的卸載。在設(shè)備完成注冊加載之后,用戶的應(yīng)用程序就可以對該設(shè)備進(jìn)行一定的操作,如open()、read()、write()等,而驅(qū)動程序就是用于實(shí)現(xiàn)這些操作,在用戶應(yīng)用程序調(diào)用相應(yīng)入口函數(shù)時(shí)執(zhí)行相關(guān)的操作,init_module()入口點(diǎn)函數(shù)則不需要完成其他如read()、write()之類功能。

上述函數(shù)之間的關(guān)系如圖11.3所示。

圖11.3設(shè)備驅(qū)動程序流程圖

2.重要數(shù)據(jù)結(jié)構(gòu)

用戶應(yīng)用程序調(diào)用設(shè)備的一些功能是在設(shè)備驅(qū)動程序中定義的,也就是設(shè)備驅(qū)動程序的入口點(diǎn),它是一個(gè)在linux/fs.h>中定義的structfile_operations結(jié)構(gòu),這是一個(gè)內(nèi)核結(jié)構(gòu),不會出現(xiàn)在用戶空間的程序中,它定義了常見文件I/O函數(shù)的入口,如下所示:

structfile_operations

{

loff_t(*llseek)(structfile*,loff_t,int);

ssize_t(*read)(structfile*filp,

char*buff,size_tcount,loff_t*offp);

ssize_t(*write)(structfile*filp,

constchar*buff,size_tcount,loff_t*offp);

int(*readdir)(structfile*,void*,filldir_t);

unsignedint(*poll)(structfile*,structpoll_table_struct*);

int(*ioctl)(structinode*,

structfile*,unsignedint,unsignedlong);

int(*mmap)(structfile*,structvm_area_struct*);

int(*open)(structinode*,structfile*);

int(*flush)(structfile*);

int(*release)(structinode*,structfile*);

int(*fsync)(structfile*,structdentry*);

int(*fasync)(int,structfile*,int);

int(*check_media_change)(kdev_tdev);

int(*revalidate)(kdev_tdev);

int(*lock)(structfile*,int,structfile_lock*);

};

這里定義的很多函數(shù)是否跟第6章中的文件I/O系統(tǒng)調(diào)用類似?其實(shí)當(dāng)時(shí)的系統(tǒng)調(diào)用函數(shù)通過內(nèi)核,最終調(diào)用對應(yīng)的structfile_operations結(jié)構(gòu)的接口函數(shù)(例如,open()文件操作是通過調(diào)用對應(yīng)文件的file_operations結(jié)構(gòu)的open函數(shù)接口而被實(shí)現(xiàn))。當(dāng)然,每個(gè)設(shè)備的驅(qū)動程序不一定要實(shí)現(xiàn)其中所有的函數(shù)操作,若不需要定義實(shí)現(xiàn)時(shí),則只需將其設(shè)為NULL即可。

structinode結(jié)構(gòu)提供了關(guān)于設(shè)備文件/dev/driver(假設(shè)此設(shè)備名為driver)的信息,structfile結(jié)構(gòu)提供關(guān)于被打開的文件信息,主要用于與文件系統(tǒng)對應(yīng)的設(shè)備驅(qū)動程序使用。structfile結(jié)構(gòu)較為重要,這里列出了它的定義:

structfile

{

mode_tf_mode;/*標(biāo)識文件是否可讀或可寫,F(xiàn)MODE_READ或FMODE_WRITE*/

dev_tf_rdev;/*用于/dev/tty*/

off_tf_pos;/*當(dāng)前文件位移*/

unsignedshortf_flags;/*文件標(biāo)志,如O_RDONLY、O_NONBLOCK和O_SYNC*/

unsignedshortf_count;/*打開的文件數(shù)目*/

unsignedshortf_reada;

structinode*f_inode;/*指向inode的結(jié)構(gòu)指針*/

structfile_operations*f_op;/*文件索引指針*/

};

linux操作系統(tǒng)文章專題:linux操作系統(tǒng)詳解(linux不再難懂)

linux相關(guān)文章:linux教程



上一頁 1 2 3 4 5 6 下一頁

評論


相關(guān)推薦

技術(shù)專區(qū)

關(guān)閉