萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 內核文件描述符機制深度解析:從 file 結構到 files_struct 管理

基於 Linux 2.6.14 內核(ARM920T 架構)源碼,深度剖析進程如何管理打開文件:file 對象、文件描述符數組、files_struct 進程打開文件表、fdtable 管理結構,並配合源碼結構體定義與關係圖解。

1. file 結構:打開文件的內核表示

進程調用 open() 後,內核將文件封裝為 struct file 實例(file 對象),定義於 include/linux/fs.h:

struct file {
    struct list_head    f_list;        // 所有打開文件全局鏈表
    struct dentry       *f_dentry;     // 目錄項(路徑解析結果)
    struct vfsmount     *f_vfsmnt;     // 掛載點指針
    struct file_operations *f_op;      // 文件操作函數表(VFS 接口)
    atomic_t            f_count;       // 引用計數
    unsigned int        f_flags;       // 打開標誌 O_RDONLY/O_WRONLY/O_CREAT...
    mode_t              f_mode;        // 訪問模式(FMODE_READ/WRITE/EXEC)
    loff_t              f_pos;         // 當前讀寫偏移量
    struct fown_struct  f_owner;       // 信號驅動 I/O 擁有者
    unsigned int        f_uid, f_gid;  // 有效 UID/GID(權限檢查用)
    struct file_ra_state f_ra;         // 預讀狀態
    unsigned long       f_version;     // 版本計數
    void                *f_security;   // LSM 安全模塊
    void                *private_data; // 設備驅動私有數據
#ifdef CONFIG_EPOLL
    struct list_head    f_ep_links;    // epoll 事件鏈表
    spinlock_t          f_ep_lock;
#endif
    struct address_space *f_mapping;   // 頁緩存映射
    struct rcu_head     f_rcuhead;     // RCU 延遲釋放
};

關鍵字段解析

  • f_op:指向 file_operations,封裝 read/write/llseek/mmap/ioctl/fsync/lock 等操作,實現多態(普通文件、設備、管道、Socket 同一接口)
  • f_pos:獨立於文件描述符,每個 file 對象獨擁偏移量(硬鏈接共享 inode 但 file 對象獨立)
  • f_count:dup()、fork() 增加,close() 減少,歸零時釋放

2. file_operations:VFS 與進程的契約

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 *);
    ssize_t (*aio_read) (struct kiocb *, char __user *, size_t, loff_t);
    ssize_t (*aio_write) (struct kiocb *, 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);
    long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);
    long (*compat_ioctl) (struct file *, unsigned int, unsigned long);
    int (*mmap) (struct file *, struct vm_area_struct *);
    int (*open) (struct inode *, struct file *);
    int (*flush) (struct file *);
    int (*release) (struct inode *, struct file *);
    int (*fsync) (struct file *, struct dentry *, int datasync);
    int (*aio_fsync) (struct kiocb *, int datasync);
    int (*fasync) (int, struct file *, int);
    int (*lock) (struct file *, int, struct file_lock *);
    ssize_t (*readv) (struct file *, const struct iovec *, unsigned long, loff_t *);
    ssize_t (*writev) (struct file *, const struct iovec *, unsigned long, loff_t *);
    ssize_t (*sendfile) (struct file *, loff_t *, size_t, read_actor_t, void *);
    ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int);
    unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long);
    int (*check_flags)(int);
    int (*dir_notify)(struct file *filp, unsigned long arg);
    int (*flock) (struct file *, int, struct file_lock *);
};

3. 文件描述符:進程視角的整數索引

  • 進程通過 整數索引(0,1,2...) 訪問 file 對象
  • 內核維護 文件描述符數組:struct file **fd_array
  • fd_array[0] = stdin、[1] = stdout、[2] = stderr
  • dup()/dup2()/fcntl(F_DUPFD) 可使多個索引指向同一 file 對象

圖1:文件描述符數組指向 file 對象

4. files_struct:進程打開文件表

定義於 include/linux/fdtable.h,掛載於 task_struct->files:

struct files_struct {
    atomic_t count;                 // 引用計數(fork 時共享,CLONE_FILES)
    spinlock_t file_lock;           // 保護下方所有字段
    struct fdtable *fdt;            // 當前生效 fdtable 指針
    struct fdtable fdtab;           // 嵌入式小型 fdtable(初始 32/64 條目)
    fd_set close_on_exec_init;      // close-on-exec 位圖
    fd_set open_fds_init;           // 打開文件位圖
    struct file * fd_array[NR_OPEN_DEFAULT]; // 內嵌文件指針數組
};

進程與文件關係圖

圖2:task_struct → files_struct → fd_array → file → dentry/inode

5. fdtable:動態擴展的文件描述符管理

struct fdtable {
    unsigned int max_fds;           // 當前數組容量
    int max_fdset;                  // 位圖長度
    int next_fd;                    // 下一個可分配 fd(分配優化)
    struct file ** fd;              // 指向 fd_array(或擴展分配的大數組)
    fd_set *close_on_exec;          // 執行時關閉標記
    fd_set *open_fds;               // 打開標記位圖(第 n 位=1 表示 fd n 打開)
    struct rcu_head rcu;            // RCU 保護
    struct files_struct *free_files;
    struct fdtable *next;           // 擴展鏈表
};

擴展機制

  • 初始使用嵌入式 fdtab.fd_array[NR_OPEN_DEFAULT](通常 32/64)
  • 超出時分配獨立 fdtable,fdt 指向新表,fd 指向 kmalloc 的大數組
  • 位圖 open_fds 實現 O(1) 分配/釋放/查找
  • next_fd 記錄下一個候選索引,避免從 0 掃描

圖3:fdtable 動態擴展與位圖管理

6. 系統調用鏈路

open() 
  → sys_open() 
    → get_unused_fd_flags()        // 分配 fd(在 files_struct 中)
    → filp_open()                  // 路徑查找、創建 file 對象
    → fd_install(fd, file)         // 綁定 fd 與 file
    → 返回 fd

read(fd, buf, count)
  → sys_read()
    → fget(fd)                     // 從 files_struct 獲取 file*,增加 f_count
    → vfs_read() → file->f_op->read()
    → fput()                       // 減少 f_count

close(fd)
  → sys_close()
    → filp_close()                 // file->f_op->release()
    → __put_unused_fd()            // 清除 fdtable 位圖、數組項
    → fput()

7. 實戰洞察

  • 文件描述符泄漏:lsof -p PID 監控 NR_OPEN 限制(默認 1024/4096,ulimit -n 調整)
  • O_CLOEXEC / FD_CLOEXEC:open(..., O_CLOEXEC) 或 fcntl(fd, F_SETFD, FD_CLOEXEC) 防止 exec() 後泄漏
  • epoll 高併發:f_ep_links 掛載就緒事件,f_ep_lock 保護
  • 容器化影響:Docker --ulimit nofile=65536:65536 提升限制,宿主機 /proc/sys/fs/nr_open 同步調整

現代內核演進(2.6.14 → 6.x)

  • files_struct 拆分:fdtable 完全分離,支持 RCU 無鎖讀取
  • file_operations 新增 iopoll、uring 相關回調
  • io_uring 繞過文件描述符直接提交 I/O,降低系統調用開銷
  • pidfd、memfd、userfaultfd 等新型文件描述符類型
copyright © 萬盛學電腦網 all rights reserved