Updated: April 19, 2023 |
Duplicate a file descriptor
#include <unistd.h> int dup( int filedes );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The dup() function duplicates the file descriptor specified by filedes. The new file descriptor refers to the same open file descriptor as the original, and shares any locks. The new file descriptor also:
Calling:
dup_filedes = dup( filedes );
is the same as:
dup_filedes = fcntl( filedes, F_DUPFD, 0 );
The new file descriptor for success, or -1 if an error occurs (errno is set).
#include <fcntl.h> #include <unistd.h> #include <sys/stat.h> #include <stdlib.h> int main( void ) { 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 ); return EXIT_SUCCESS; } return EXIT_FAILURE; }
Safety: | |
---|---|
Cancellation point | No |
Interrupt handler | No |
Signal handler | Yes |
Thread | Yes |