I have a file on the filesystem. I'm opening the file with the open(2)
function to get the file descriptor to that file.
Now I remove the file. But I still have the file descriptor, so I can read and write to that file without problems, because the filesystem will not remove the file allocation of my file until last file descriptor is closed.
But after I remove the file, and while I still hold the file descriptor, can I somehow re-create (re-bind) the filename to that file descriptor? So the file would appear again on the filesystem, so it won't be removed when I close the file descriptor? (all I have is an opened file descriptor and nothing else).
I'm mostly interested if this can be done on macOS (on Linux/glibc it seems to be possible to do by using linkat
with the AT_EMPTY_PATH
flag).
2 Answers 2
As you mention, linkat
on Linux allows this to be done using AT_EMPTY_PATH
, but only for privileged processes. (There’s some discrepancy between the man page and the current implementation; see the commit introducing "flink
" and the commit reverting it for details.) It can also be done through /proc
.
The macOS version of linkat
doesn’t support this, and I’m not aware of any other way of achieving this.
It seems that fclonefileat(2)
on macOS 10.12 and later should be able to do the job.