When you are curious about the POSIX features, especially those that seem to duplicate themselves, it is usually good to check the standard itself . Below you will usually see examples, as well as discussions about the implementation (and existence) of both.
In this case:
The following sections are informative.
Examples
Redirecting standard output to a file
The following example closes the standard output for current processes, reassigns standard output to go to the file referenced by pfd , and closes the original file descriptor for cleaning.
#include <unistd.h> ... int pfd; ... close(1); dup(pfd); close(pfd); ...
Error message redirection
The following example redirects messages from stderr to stdout .
#include <unistd.h> ... dup2(2, 1); // 2-stderr; 1-stdout ...
Using the application
Absent.
Justification
The dup() and dup2() functions are redundant. Their services are also provided by the fcntl() function. They are included in this volume of IEEE Std 1003.1-2001 mainly for historical reasons, as many existing applications use them.
While the short code segment shown is very similar in behavior to dup2() , the corresponding implementation based on other functions defined in this volume of IEEE Std 1003.1-2001 is much more complicated. The least obvious is the possible effect of the signal capture function, which can be called between steps, and allocate or free file descriptors. This can be avoided by blocking the signals.
The dup2() function is not deprecated since it is a safe version of the functionality provided in an unsafe version of the fcntl() . It is used in POSIX Ada bindings.
The dup2() function is not intended to be used in critical areas as a synchronization mechanism.
In the [EBADF] description, the case where fildes is out of range is covered by this case when fildes are invalid. The descriptions for fildes and fildes2 different because the only kind of invalidity that matters to fildes2 is out of range; that is, it does not matter if fildes2 to an open file when calling dup2() .
Future directions
Absent.
see also
close() , fcntl() , open() , IEEE Std 1003.1-2001 basic definitions volume, <unistd.h>
Change history
The first one was released in release 1. Derived from number 1 from SVID.