Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Linux 內核 struct file 結構體詳解:設備驅動核心數據結構

編輯:Linux 系統常見問題解答

struct file 定義於 <linux/fs.h>,是設備驅動中僅次於 file_operations 的核心結構。注意:它與用戶態 C 庫的 FILE* 完全無關——前者為內核對象,後者為用戶態流封裝。

生命週期

  • 創建:open 系統調用時由 VFS 分配並初始化。
  • 傳遞:作為 filp 指針傳給驅動的各個 file_operations 方法(read/write/ioctl…)。
  • 銷毀:最後一次 close(引用計數歸零)時由 VFS 釋放。

內核慣例稱其指針為 filp(file pointer),避免與結構體名混淆。

關鍵字段詳解

字段類型含義與用法
f_modemode_t文件訪問模式,FMODE_READ/FMODE_WRITE 位標識可讀/可寫。驅動通常無需檢查,VFS 已在調用前驗證權限。
f_posloff_t (64-bit)當前讀寫偏移。驅動可讀取,但不應直接修改;read/write 通過最後一個參數 loff_t* 更新。llseek 例外,專門修改此值。
f_flagsunsigned intopen 時的標誌:O_RDONLY/O_NONBLOCK/O_SYNC… 驅動需關注 O_NONBLOCK 實現非阻塞;讀寫權限用 f_mode 而非此字段。定義於 <linux/fcntl.h>。
f_opstruct file_operations*指向操作函數表。open 時由驅動設置(或默認關聯 inode->i_fop)。可動態替換,實現「方法重載」:如 /dev/null、/dev/zero 同主設備號,open 根據次設備號替換 f_op。
private_datavoid*驅動私有數據指針。open 前為 NULL,驅動可在 open 中分配結構體掛載,release 中釋放。跨系統調用保持狀態的關鍵。
f_dentrystruct dentry*關聯目錄項。驅動少用,主要通過 filp->f_dentry->d_inode 訪問 inode 獲取設備號等信息。

實戰提示

  • 驅動不創建 struct file,僅操作 VFS 傳入的實例。
  • 利用 private_data 存儲設備上下文(如緩衝區指針、硬件寄存器映射基址),避免全局變量污染。
  • 若需實現多種行為共用主設備號,在 open 中根據 iminor(inode) 動態設置 filp->f_op 指向不同 file_operations 實例。
Copyright © Windows教程網 All Rights Reserved