Monday, November 15, 2021

[SOLVED] 2 file descriptors for the same file

Issue

I have a file descriptor >0 for a file that is already opened. I want to add a second file descriptor to that file. I know this is possible if I open the file with the second file descriptor again but the problem is that in that point of my code I don't know the name of the file.

So I was wondering if I can just do that: fd2 = fd1;


Solution

You may duplicate the file descriptor, returning a new, distinct handle to the same open file description, with either dup

#include <unistd.h>
int fd2 = dup(fd1);

or with fcntl/F_DUPFD

#include <fcntl.h>
int fd2 = fcntl(fd1, F_DUFPD, 0); // consider F_DUPFD_CLOEXEC !

Because fd2 and fd1 now refer to the same open file description, they "share" certain attributes of the underlying open file description:

  • status flags (nonblocking, append-only, etc.)
  • access mode (read-only, read-write, write-only)
  • file position (reading/seeking on one will be reflected in the other)
  • record locks (as with POSIX struct flock locks)

If you change one of the above on fd2, that change will be visible in fd1 since, again, both refer to the same underlying I/O construct. The same thing happens when file descriptors are duplicated across processes ("inherited").

The descriptors themselves have only one interesting attribute of their own, FD_CLOEXEC, which controls whether or not the descriptor will be preserved (inherited) across an execve call. This may differ for each descriptor.



Answered By - pilcrow