dup2(2)dup2(2)NAMEdup2 - duplicate an open file descriptor to a specific slot
SYNOPSISDESCRIPTION
fildes is a file descriptor obtained from a or system call.
fildes2 is a non-negative integer less than the maximum value allowed
for file descriptors.
causes fildes2 to refer to the same file as fildes. If fildes2 refers
to an already open file, the open file is closed first.
The file descriptor returned by has the following in common with
fildes:
· Same open file (or pipe).
· Same file pointer (that is, both file descriptors share one
file pointer.)
· Same access mode (read, write or read/write).
· Same file status flags (see fcntl(2),
The new file descriptor is set to remain open across system calls. See
fcntl(2).
This routine is found in the C library. Programs using but not using
other routines from the Berkeley importability library (such as the
routines described in bsdproc(3C)) should not give the option to ld(1).
RETURN VALUE
Upon successful completion, returns the new file descriptor as a non-
negative integer, fildes2. Otherwise, it returns −1 and sets to indi‐
cate the error.
ERRORS
fails if the following is true:
fildes is not a valid open file descriptor or fildes2 is
not in the range of legal file descriptors.
An attempt to close
fildes2 was interrupted by a signal. The file is
still open.
WARNINGS
A multithreaded application or an application with a signal handler can
exhibit a race between on one thread and another kernel call that
assigns a new file descriptor while running on a second thread or sig‐
nal handler. If fildes2 is free before the call was made, the other
thread or signal handler may win the race and acquire that descriptor
(e.g., in an call). The thread calling can then close this file and
reuse the descriptor. This results in multiple functions improperly
referring to the same file.
This race can be avoided either by ensuring that fildes2 references an
open file before calling or by providing user-level synchronization (or
signal disabling) which makes sure that the thread and another thread
or signal handler don't make competing calls into the kernel at the
same time.
SEE ALSOclose(2), creat(2), dup(2), exec(2), fcntl(2), open(2), pipe(2), privi‐
leges(5).
STANDARDS CONFORMANCEdup2(2)