-
打開
- int open(struct inode *inode,struct file *filp);
- 模塊使用計數加1
- 識別次設備號
- 硬件操作
- 檢查設備相關錯誤(諸如設備未就緒或類似的硬件問題)
- 如果設備是首次打開,則對其初始化
- 如果有中斷操作,申請中斷處理程序
-
關閉
- int release(struct inode *inode,struct file *filp);
- 模塊使用計數減1
- 釋放由open分配的,保存在filp>private_data里的所有內容。
- 硬件操作:
- 如果申請了中斷,則釋放中斷中中斷處理程序。
- 在最后一次關閉操作時關閉設備。
-
read/write
- ssize_t read(struct file *filp,char __user *buff,sieze_t count,loff_t *offp);
- ssize_t write(struct file *filp,const char __user *buff,size_t count,loff_t *offp);
-
用戶空間和內核空間之間的數據拷貝過程
- 不能簡單的用指針操作或者memcpy來進行數據的拷貝
- 用戶空間的數據是可以被換出的,會產生一個頁面失效的異常
- 用戶空間的地址無法在內核空間中使用。
-
用戶空間和內核空間之間進行數據拷貝的函數
- unsigned long copy_from_user(void *to,const void __user *from,unsigned long count);
- unsigned long copy_to_user(void __user *to,const void *from,unsigned long count);
- 讀設備模板
ssize_t xxx_read(struct *filp,char __user *buf,size_t count,loff_t*f_fpos)
{
copy_to_user(buf,---)
}
-
- 寫設備模板
ssize_t xxx_write(struct file *filp,const char __user *buf,size_t count,loff_t *f_ops)
{
?copy_from_user(--,buf,--);
}
-
ioctl函數
- 為設備驅動程序執行命令提供了一個特有的入口點
- 用來設置或者讀取設備的屬性信息
- int ioctl(struct inode *inode,struct file *filp,unsigned int cmd,unsigned long arg);
- cmd參數的定義
- 不推薦使用0x1,0x2之類的值
- linux對ioctl()的cmd參數有特殊的定義
- 設別號(type) ? 序列號(number) 方向(direction) 數據尺寸(size)
- 8bit ? ? ? ? ? ? ? ? 8bit ? ? ? ? ? ? ? ? ? ?2bit ? ? ? ? ? ? ? ? 13/14bit
-
構造命令編號的宏:
- _IO(type,nr)用于構造物參數的命令編號;
- _IOR(type,nr,datatype)用于構造從驅動程序中讀取數據的命令編號;
- _IOw(type,nr,datatype)用于寫入數據的命令
-
_IOWR(type,nr,datatype)用于雙向傳輸。
- type,nr通過參數傳入,而size位字段通過對datatype參數的sizeof獲得。
- ioctl函數模板
int xxx_ioctl(struct inode *inode,struct file *filp,unsigned int cmd,unsigned long arg)
{
-----
switch(cmd)
{
case xxx_cmd1:
----
break;
case xxx_cmd2:
----
break;
default:
return -ENOTTY;
}
return 0;
}
- 字符設備驅動結構:
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
