文件/套接字描述符表

时间:2015-10-19 03:53:02

标签: linux-kernel file-descriptor

我很想知道如何在Linux中实现每进程文件/套接字描述符表。具体而言,使用哪些数据结构和算法来实现它并使其保持高效。

提前致谢!

1 个答案:

答案 0 :(得分:1)

进程打开的文件由struct files_struct管理,该文件位于进程的struct task_struct

struct task_struct {
    ...
    /* open file information */
    struct files_struct *files;

每进程文件描述符表(fdt)位于struct files_struct

struct files_struct {
    ...
    struct fdtable __rcu *fdt;

当进程尝试打开文件时,它会发出一个打开的系统调用。这将调用sys_open。这基本上就是代码流程:

sys_open(filename, …)
    // 1)   copy filename from user space
    getname(filename)
            strncpy_from_user()
    // 2)  get first unused file descriptor (will be returned to process)
    int fd = get_unused_fd()
        struct files_struct *files = current->files
    // 3) get file from filesystem
    struct file *f = file_open(filename)
        open_namei
            // lookup operation for filesystem
            dentry = cached_lookup or real_lookup 
            // initializes file struct
            dentry_open 
    // 4) install file returned by filesystem into file descriptor table for the process
    fd_install
        current->files->fd[fd] = file

该进程返回索引到打开文件的文件描述符表。