duplicate a file descriptor
#include <unistd.h> int dup( int filedes );
The dup() function duplicates the file descriptor given by the argument filedes. The new file descriptor refers to the same open file descriptor as the original file descriptor, and shares any locks. The new file descriptor is identical to the original, in that:
Changing the position with one descriptor will result in a changed position in the other.
The call
dup_filedes = dup( filedes );
is equivalent to:
dup_filedes = fcntl( filedes, F_DUPFD, 0 );
If successful, the new file descriptor is returned to be used with the other functions that operate on the file. Otherwise, -1 is returned, and 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 = dup( filedes ); if( 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(), dup2(), eof(), errno, exec... functions, fcntl(), filelength(), fileno(), fstat(), isatty(), lseek(), open(), read(), setmode(), sopen(), stat(), tell(), umask(), write()