Search code examples
cfilelinux-kernelinode

How to open and read file from `struct inode *` in Linux kernel


I want to check the content of a file from Linux Kernel v3.0.8 knowing only struct inode *. I only need to read the beginning of a file pointed by this inode, then close and return. I don't care about additional information like filename/mountpoint etc.. In fact, the file may not have the name (like deleted but still open). Is it possible?


Solution

  • I finally did it like this:

    1. This is needed.
    struct path root;
    struct file *filerd;
    
    1. Get the init task fs root.
    task_lock(&init_task);
    get_fs_root(init_task.fs, &root);
    task_unlock(&init_task);
    
    1. Change dentry to this file:
    root.dentry = d_find_alias(inode);
    
    1. Open file:
    filerd = file_open_root(root.dentry->d_parent, root.mnt,
                            root.dentry->d_name.name, O_RDONLY);
    

    It worked for every process I tested and for different mount points, which surprised me.