Implementation status: partially implemented

Synopsis

#include <unistd.h>

int dup(int fildes);
int dup2(int fildes, int fildes2);

Description

The functions duplicate an open file descriptor.

Arguments:

fildes - the file descriptor to be duplicated.
fildes2 - the file descriptor received as a result of duplication.

The dup() function duplicates an existing object descriptor and returns its value to the calling process. The argument fildes is a small non-negative integer index in the per-process descriptor table. The new descriptor returned by the call is the lowest numbered descriptor currently not in use by the process.

In dup2() function, the value of the new descriptor fildes2 is specified as a second argument. If fildes and fildes2 are equal, then dup2()just returns fildes2; no other changes are made to the existing descriptor. Otherwise, if descriptor fildes2 is already in use, it is first deallocated as if a close(2) call had been done.

Return value

The resulting file descriptor is returned on success, otherwise -1 is returned and errno set to indicate the error.

Errors

For the dup() function:

[EBADF] - The fildes argument is not a valid open file descriptor.
[EMFILE] - All file descriptors available to the process are currently open.

For the dup2() function:

[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.
[EIO] - An I/O error occurred while attempting to close fildes2.

Implementation tasks

  • Implement error detection for errors described above.