Create a hard link from a file handle on Unix?

前端 未结 3 1801
再見小時候
再見小時候 2021-02-07 03:39

If I\'ve got a handle to an open file, is it possible to create a hard link to that file after all references to it have been removed from the filesystem?

For example, s

3条回答
  •  名媛妹妹
    2021-02-07 03:49

    The newly released linux 3.11 offers a solution to this problem with the new O_TMPFILE open(2) flag. With this flag you can create an "invisible" file (i.e. an inode with no hardlinks) in some file system (specified by a directory in that file system). Then, after the file is fully set up, you can create a hardlink using linkat. It works like this:

    fd = open("/tmp", O_TMPFILE | O_RDWR, 0600);
    // write something to the file here
    // fchown()/fchmod() it
    linkat(fd, "", AT_FDCWD, "/tmp/test", AT_EMPTY_PATH);
    

    Note that aside from the >=3.11 kernel requirement, this also requires support from the underlying file system (I tried the above snippet on ext3 and it worked, but it did not seem to work on btrfs).

提交回复
热议问题