duplicate a file descriptor
#include <unistd.h> int dup2( int filedes , int filedes2 );
The dup2() function duplicates the file descriptor given by the argument filedes. The new file descriptor is identical to the original, in that:
The number of the new descriptor is filedes2. If a file already is opened with this descriptor, the file is closed before the duplication is attempted.
The call
dup_filedes = dup2( filedes, filedes2 );
is equivalent to
close( filedes2 );
dup_filedes = fcntl( filedes , F_DUPFD, filedes2 );
The value of filedes2, or -1 if an error occurs; errno is set to indicate the error.
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
void main()
{
int filedes , dup_filedes ;
filedes = open( "file",
O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP );
if( filedes != -1 ) {
dup_filedes = 4;
if( dup2( filedes, dup_filedes ) != -1 ) {
/* process file */
close( dup_filedes );
}
close( filedes );
}
}
POSIX 1003.1
| Safety: | |
|---|---|
| Interrupt handler | No |
| Signal handler | Yes, but modifies errno |
| Thread | Yes |
chsize(), close(), creat(), dup(), eof(), errno, exec... functions, fcntl(), filelength(), fileno(), fstat(), isatty(), lseek(), open(), read(), setmode(), sopen(), stat(), tell(), umask(), write()