dup2 -- Associate Second Handle with Open File

Format

#include <io.h>
int dup2(int handle1, int handle2);

Language Level: XPG4, Extension
dup2 makes handle2 refer to the currently open file associated with handle1. You can carry out operations on the file using either file handle because all handles associated with a given file use the same file pointer.

handle2 will point to the same file as handle1, but will retain the file access mode (text or binary) that it had before duplication. In addition, if handle2 was originally opened with the O_APPEND flag, it will also retain that attribute. If handle2 is associated with an open file at the time of the call, that file is closed.

Warning!
Both handles share a single file position. If you reposition a file using handle1, the position in the file returned by handle2 will also change.

If you duplicate a file handle for an open stream (using fileno), the resulting file handle has the same restrictions as the original file handle.

Note: In earlier releases of the C/C++ run-time library, dup2 began with an underscore (_dup2). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, IBM C and C++ Compilers will map _dup2 to dup2 for you.

Return Value
dup2 returns 0 to indicate success. It returns -1 if an error occurs and sets errno to one of the following values:

Value Meaning
EBADF The file handle is not valid.
EMFILE No more file handles are available.
EOS2ERR The call to the operating system was not successful.

Example



close -- Close File Associated with Handle
creat -- Create New File
dup -- Associate Second Handle with Open File
open -- Open File
_sopen -- Open Shared File
<io.h>