Open file by inode

前端 未结 2 1334
甜味超标
甜味超标 2021-01-11 10:54

Is it possible to open a file knowing its inode?

ls -i /tmp/test/test.txt
529965 /tmp/test/test.txt

I can provide path, inode (above 529965

2条回答
  •  盖世英雄少女心
    2021-01-11 11:32

    Not exactly what you are asking, but (as hinted by zwol) both Linux and NetBSD/FreeBSD provide the ability to open files using previously created “handles”: These are inode-like persistent names that identify a file on a file system.

    On *BSD (getfh and fhopen) using this is as simple as:

    #include 
    #include 
    
    
    fhandle_t file_handle;
    getfh("", &file_handle);  // Or `getfhat` for the *at-style API
    
    // … possibly save handle as bytes somewhere and recreate it some time later …
    
    int fd = fhopen(&file_handle, O_RDWR);
    

    The last call requiring the caller to be root however.

    The Linux name_to_handle_at and open_by_handle_at system calls are similar, but a lot more explicit and require the caller to keep track of the relevant file system mount IDs/UUIDs themselves, so I'll humbly link to the detailed example in the manpage instead. Beware, that the example is not complete if you are looking to persist the handles across reboots; one has to convert the received mount ID to a persistent filesystem identifier, such as a filesystem UUID, and convert that back to a mount ID later on. In essence they do the same however. And just like on *BSD using the later system call requires elevated privileges (CAP_DAC_READ_SEARCH to be exact).

提交回复
热议问题