Relinking an anonymous (unlinked but open) file

A patch for a proposed Linux flink() system call was submitted several years ago, but when Linus stated “there is no way in HELL we can do this securely without major other incursions”, that pretty much ended the debate on whether to add this.

Update: As of Linux 3.11, it is now possible to create a file with no directory entry using open() with the new O_TMPFILE flag, and link it into the filesystem once it is fully formed using linkat() on /proc/self/fd/fd with the AT_SYMLINK_FOLLOW flag.

The following example is provided on the open() manual page:

    char path[PATH_MAX];
    fd = open("/path/to/dir", O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR);

    /* File I/O on 'fd'... */

    snprintf(path, PATH_MAX,  "/proc/self/fd/%d", fd);
    linkat(AT_FDCWD, path, AT_FDCWD, "/path/for/file", AT_SYMLINK_FOLLOW);

Note that linkat() will not allow open files to be re-attached after the last link is removed with unlink().

Leave a Comment