Kernel version:2.6.14
CPU architecture:ARM920T
作為文件的使用者,行程理所當然要將所使用的文件記錄於自己的控制塊 task_struct 中。另外,由於行程對應的程式本身也是一個文件,因此行程控制塊還必須記錄這個文件的相關資訊。由於 OS 要為所有行程提供服務,因此還要維護一個記錄所有行程打開文件的總表。
1. 文件物件
當行程透過 open 系統調用打開一個文件時,系統調用找到該文件後,會把它封裝到一個 file 結構的實例中提供給行程,這個實例稱為 file 物件。file 結構定義如下:
struct file {
struct list_head f_list; //所有打開文件的鏈表
struct dentry *f_dentry; //文件的 dentry
struct vfsmount *f_vfsmnt; //文件目錄的 VFS 安裝點指針
struct file_operations *f_op; //指向文件操作函數集的指針
atomic_t f_count; //訪問本文件的行程數目計數器
unsigned int f_flags; //訪問類型
mode_t f_mode; //訪問模式
loff_t f_pos; //文件當前的讀寫位置
struct fown_struct f_owner;
unsigned int f_uid, f_gid; //文件所有者 ID 和用戶組 ID
struct file_ra_state f_ra;
unsigned long f_version;
void *f_security;
void *private_data;
struct address_space *f_mapping;
};
結構中的 f_uid 為文件所有者的 ID,f_gid 為所有者所在組的 ID。這樣一個文件可能面臨三種用戶的訪問:文件所有者、同組用戶、其他用戶。內核在處理訪問請求時,會根據行程的 f_uid、f_gid 以及訪問模式來判斷是否具備訪問權限。對於一個用戶來說,有讀、寫、執行三種權限,與三種用戶共有 9 種組合,即文件的訪問權限可用 9 個 bit 表示,並保存在文件的 dentry 中。
結構中的 f_pos 記錄了行程對文件讀寫位置的當前值,可透過 llseek 函數移動。
結構中的 f_op 指向 file_operations,該結構封裝了對文件進行操作的函數:
struct file_operations {
struct module *owner;
loff_t (*llseek) (struct file *, loff_t, int);
ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
int (*readdir) (struct file *, void *, filldir_t);
unsigned int (*poll) (struct file *, struct poll_table_struct *);
int (*ioctl) (struct inode *, struct file *, unsigned int, unsigned long);
int (*mmap) (struct file *, struct vm_area_struct *);
int (*open) (struct inode *, struct file *);
int (*release) (struct inode *, struct file *);
int (*fsync) (struct file *, struct dentry *, int datasync);
int (*lock) (struct file *, int, struct file_lock *);
};
從上面的程式碼可以看到,結構中是一系列函數的指針,有我們比較熟悉的 read、open、write、close 等。行程就是透過這些函數訪問文件的,file_operations 正是 Linux 虛擬文件系統 VFS 與行程之間的介面。