dup()

QNX SDP8.0C Library ReferenceAPIDeveloper

Duplicate a file descriptor

Synopsis:

#include <unistd.h>

int dup( int filedes );

Arguments:

filedes
The file descriptor that you want to duplicate.

Library:

libc

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

Description:

The dup() function duplicates the file descriptor specified by filedes and returns the new file descriptor. The number of this new descriptor is the lowest available (i.e., not already open) file descriptor and it refers to the same open file description as the original and shares any locks.

The new file descriptor also:
  • 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).
Calling:
dup_filedes = dup( filedes );
is the same as:
dup_filedes = fcntl( filedes, F_DUPFD, 0 );

The two file descriptors do not share file descriptor flags, so the close-on-exec flag (FD_CLOEXEC) for the duplicate descriptor is off.

Returns:

The new file descriptor for success, or -1 if an error occurs (errno is set).

Errors:

EBADF
The file descriptor, filedes, isn't a valid open file descriptor.
EMFILE
All file descriptors available to the process are currently open.
ENOSYS
The dup() function isn't implemented for the filesystem specified by filedes.

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 = dup( filedes );
        if( 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: