I have an open device descriptor, where I don’t know the device name and the options
passed to open(…).
I want to open a new device descriptor with the same options passed to open.
int newFd = copy(referenceFd);
Where copy would do the job. dup() is certainly the wrong choice as a further ioctl() on newFd would also alter the referenceFd, therefore I want to open a new descriptor.
Is there a system call which provides such functionality?
I have not been able to find something yet.
First, get the descriptor flags of file descriptor
fdusingThen, reopen the descriptor using the Linux-specific
/proc/self/fd/fdentry:The reopened file descriptor is then in
newfd.Note that you most likely want to make sure
O_TRUNC(truncate the file) andO_EXCL(fail if exists) are not in the flags, to avoid the cases where reopening using the exact original flags would cause unwanted results.You do not want to use
lstat(), because that opens up a race condition with respect to rename — a user renaming the target file between thelstat()and theopen()in above code. The above avoids that completely.If you don’t want to be Linux-specific, add code that tries the same with
/dev/fd/fdif the above fails. It is supported in some Unix systems (and most Linux distros too).