NAME [Toc] [Back]
dup2 - duplicate an open file descriptor to a specific slot
SYNOPSIS [Toc] [Back]
int dup2(int fildes, int fildes2);
DESCRIPTION [Toc] [Back]
fildes is a file descriptor obtained from a creat(), open(), dup(),
fcntl(), or pipe() system call.
fildes2 is a non-negative integer less than the maximum value allowed
for file descriptors.
dup2() 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 dup2() has the following in common
+ Same open file (or pipe).
+ Same file pointer (that is, both file descriptors share one
+ Same access mode (read, write or read/write).
+ Same file status flags (see fcntl(2), F_DUPFD).
The new file descriptor is set to remain open across exec() system
calls. See fcntl(2).
This routine is found in the C library. Programs using dup2() but not
using other routines from the Berkeley importability library (such as
the routines described in bsdproc(3C)) should not give the -lBSD
option to ld(1).
RETURN VALUE [Toc] [Back]
Upon successful completion, dup2() returns the new file descriptor as
a non-negative integer, fildes2. Otherwise, it returns -1 and sets
errno to indicate the error.
ERRORS [Toc] [Back]
dup2() fails if the following is true:
[EBADF] fildes is not a valid open file descriptor or fildes2
is not in the range of legal file descriptors.
[EINTR] An attempt to close fildes2 was interrupted by a
signal. The file is still open.
Hewlett-Packard Company - 1 - HP-UX 11i Version 2: Sep 2004
WARNINGS [Toc] [Back]
A multithreaded application or an application with a signal handler
can exhibit a race between dup2() on one thread and another kernel
call that assigns a new file descriptor while running on a second
thread or signal handler. If fildes2 is free before the dup2() call
was made, the other thread or signal handler may win the race and
acquire that descriptor (e.g., in an open() call). The thread calling
dup2() 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 dup2(), or by providing user-level
synchronization (or signal disabling) which makes sure that the dup2()
thread and another thread or signal handler don't make competing calls
into the kernel at the same time.
SEE ALSO [Toc] [Back]
close(2), creat(2), dup(2), exec(2), fcntl(2), open(2), pipe(2).
STANDARDS CONFORMANCE [Toc] [Back]
dup2(): AES, SVID2, SVID3, XPG3, XPG4, FIPS 151-2, POSIX.1
Hewlett-Packard Company - 2 - HP-UX 11i Version 2: Sep 2004 [ Back ]