file結構體

1.1 struct file
  struct file結構體定義在include/linux/fs.h中定義。文件結構體代表一個打開的文件,系統中的每個打開的文件在內核空間都有一個關聯的 struct file。它由內核在打開文件時創建,並傳遞給在文件上進行操作的任何函數。在文件的所有實例都關閉後,內核釋放這個數據結構。在內核創建和驅動源碼中,struct file的指針通常被命名爲file或filp。

struct file 的最重要成員在這展示.
1.mode_t f_mode;
文件模式確定文件是可讀的或者是可寫的(或者都是), 通過位 FMODE_READ 和FMODE_WRITE. 你可能想在你的 open 或者 ioctl 函數中檢查這個成員的讀寫許可, 但是不需要檢查讀寫許可, 因爲內核在調用你的方法之前檢查. 當文件還沒有爲那種存取而打開時讀或寫的企圖被拒絕, 驅動甚至不知道這個情況.
2.loff_t f_pos;
當前讀寫位置. loff_t 在所有平臺都是 64 位( 在 gcc 術語裏是 long long ). 驅動可以讀這個值,如果它需要知道文件中的當前位置, 但是正常地不應該改變它; 讀和寫應當使用它們作爲最後參數而收到的指針來更新一個位置, 代替直接作用於 filp->f_pos. 這個規則的一個例外是在 llseek 方法中, 它的目的就是改變文件位置.
3.unsigned int f_flags;
這些是文件標誌, 例如 O_RDONLY, O_NONBLOCK, 和 O_SYNC. 驅動應當檢查O_NONBLOCK 標誌來看是否是請求非阻塞操作; 其他標誌很少使用. 特別地, 應當檢查讀/寫許可, 使用 f_mode 而不是f_flags. 所有的標誌在頭文件

ifdef __NEED_I_SIZE_ORDERED

seqcount_t i_size_seqcount;

endif

struct timespec i_atime;
struct timespec i_mtime;
struct timespec i_ctime;
unsigned int i_blkbits;
blkcnt_t i_blocks;
unsigned short i_bytes;
umode_t i_mode;
spinlock_t i_lock;
struct mutex i_mutex;
struct rw_semaphore i_alloc_sem;
const struct inode_operations *i_op;
const struct file_operations *i_fop;
struct super_block *i_sb;
struct file_lock *i_flock;
struct address_space *i_mapping;
struct address_space i_data;

ifdef CONFIG_QUOTA

struct dquot *i_dquot[MAXQUOTAS];

endif

struct list_head i_devices;
union {
struct pipe_inode_info *i_pipe;
struct block_device *i_bdev;
struct cdev *i_cdev; //該成員表示字符設備的內核的 內部結構。當inode指向一個字符設備文件時,該成員包含了指向struct cdev結構的指針,其中cdev結構是字符設備結構體。
};
int i_cindex;

__u32 i_generation;

ifdef CONFIG_DNOTIFY

unsigned long i_dnotify_mask;
struct dnotify_struct *i_dnotify;

endif

ifdef CONFIG_INOTIFY

struct list_head inotify_watches;
struct mutex inotify_mutex;

endif

unsigned long i_state;
unsigned long dirtied_when;

unsigned int i_flags;

atomic_t i_writecount;

ifdef CONFIG_SECURITY

void *i_security;

endif

void *i_private;
};

  我們在進程中打開一個文件F,實際上就是要在內存中建立F的dentry,和inode結構,並讓它們與進程結構聯繫來,把VFS中定義的接口給接起來。我們來看一看這個經典的圖:
file結構體詳解
這裏寫圖片描述

下圖爲多個進程打開同一文件的情況:
file結構體詳解
這裏寫圖片描述

發佈了50 篇原創文章 · 獲贊 21 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章