Synopsis

#include <unistd.h>

int dup(int fildes);

int dup2(int fildes, int fildes2);

Status

Partially implemented

Conformance

IEEE Std 1003.1-2017

Description

The dup() function provides an alternative interface to the service provided by fcntl() using the F_DUPFD command. The call dup(fildes) shall be equivalent to:

fcntl(fildes, F_DUPFD, 0);

The dup2() function shall cause the file descriptor fildes2 to refer to the same open file description as the file descriptor fildes and to share any locks, and shall return fildes2 . If fildes2 is already a valid open file descriptor, it shall be closed first, unless fildes is equal to fildes2 in which case dup2() shall return fildes2 without closing it. If the close operation fails to close fildes2 , dup2() shall return -1 without changing the open file description to which fildes2 refers. If fildes is not a valid file descriptor, dup2() shall return -1 and shall not close fildes2 . If fildes2 is less than 0 or greater than or equal to OPEN_MAX, dup2() shall return -1 with errno set to EBADF.

Upon successful completion, if fildes is not equal to fildes2 , the FD_CLOEXEC flag associated with fildes2 shall be cleared. If fildes is equal to fildes2 , the FD_CLOEXEC flag associated with fildes2 shall not be changed. If fildes refers to a typed memory object, the result of the dup2() function is unspecified.

Return value

Upon successful completion a non-negative integer, namely the file descriptor, shall be returned; otherwise, -1 shall be returned and errno set to indicate the error.

Errors

The dup() function shall fail if:

  • EBADF - The fildes argument is not a valid open file descriptor.

  • EMFILE - All file descriptors available to the process are currently open.

The dup2() function shall fail if:

  • EBADF - The fildes argument is not a valid open file descriptor or the argument fildes2 is negative or greater than or equal to OPEN_MAX.

  • EINTR - The dup2() function was interrupted by a signal.

The dup2() function may fail if:

  • EIO - An I/O error occurred while attempting to close fildes2 .

Tests

Untested

Known bugs

None

See Also

  1. Standard library functions
  2. Table of Contents