dup2()

QNX SDP8.0C Library ReferenceAPIDeveloper

Duplicate a file descriptor, specifying the new descriptor

Synopsis:

#include <unistd.h>

int dup2( int filedes, 
          int filedes2 );

Arguments:

filedes
The file descriptor that you want to duplicate.
filedes2
The number that you want to use for the new file descriptor.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The dup2() function duplicates the file descriptor specified by filedes. The number of the new file descriptor will be filedes2. If a file already is opened with this descriptor, the file is closed before the duplication is attempted, unless filedes2 is the same as filedes, in which case dup2() returns filedes2 without closing the file.

The new file descriptor:

  • references the same file or device
  • has the same open mode (read and/or write)
  • has an identical file position to the original (changing the position with one descriptor results in a changed position in the other)

Returns:

The value of filedes2 for success, or -1 if an error occurs (errno is set).

Errors:

EBADF
The filedes argument isn't a valid open file descriptor, or filedes2 is out of range.
EINTR
The function was interrupted by a signal.
EMFILE
All file descriptors available to the process are currently open.

Examples:

#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 = 4;
        if( dup2( filedes, dup_filedes ) != -1 ) {
            /* process file */
            /* ... */
        
            close( dup_filedes );
        }
        close( filedes );
        
        return EXIT_SUCCESS;
    }
    
    return EXIT_FAILURE;
}

Classification:

POSIX 1003.1

Safety:
Cancellation pointNo
Signal handlerYes
ThreadYes
Page updated: