dup2
Purpose
Duplicates an open file descriptor.
Library
Berkeley Library (libbsd.a)
Syntax
int dup2 (oldfd, newfd)
int oldfd, newfd;
Description
The dup2 subroutine duplicates the file descriptor,
oldfd, to the new file descriptor, newfd. When you
specify a value of newfd that is already in use, the
descriptor is deallocated as if a close system call had
been issued.
The oldfd parameter is a small nonnegative integer index
in the descriptor table. Its value must be less than
the size of the descriptor table obtained by the
getdtablesize subroutine.
Note: Since newfd and oldfd are duplicate references to
an open file once the dup2 subroutine has been called,
the read, write, and lseek system calls move a single
pointer into that file. Append mode and both non-
blocking I/O and asynchronous I/O options are then shared
between the references. Therefore, if you want to place
a separate pointer in the file, you should issue an addi-
tional open system call to obtain a different object ref-
erence instead of using the dup2 subroutine.
The new file descriptor is set to remain open across exec
system calls. (For more information about file control,
see "fcntl.h.")
Return Value
When the call succeeds, a file descriptor (nonnegative
integer) is returned. If the dup2 subroutine fails, a
value of -1 is returned and errno is set to indicate the
error.
Diagnostics
The dup2 subroutine fails if one or more of the following
is true:
EBADF The oldfd parameter is not a valid open file
descriptor.
EINVAL The newfd parameter is not between 0 and 199,
which is the valid range for file descriptors.
Related Information
In this book: "accept," "close," "dup," "getdtablesize,"
"open," "pipe," "socket," "socketpair," and "fcntl.h,"