Team BBL
Previous Page Next Page

3.12. dup and dup2 Functions

An existing file descriptor is duplicated by either of the following functions.

#include <unistd.h>

int dup(int filedes);

int dup2(int filedes, int filedes2);

Both return: new file descriptor if OK, 1 on error


The new file descriptor returned by dup is guaranteed to be the lowest-numbered available file descriptor. With dup2, we specify the value of the new descriptor with the filedes2 argument. If filedes2 is already open, it is first closed. If filedes equals filedes2, then dup2 returns filedes2 without closing it.

The new file descriptor that is returned as the value of the functions shares the same file table entry as the filedes argument. We show this in Figure 3.8.

Figure 3.8. Kernel data structures after dup(1)


In this figure, we're assuming that when it's started, the process executes

    newfd = dup(1);

We assume that the next available descriptor is 3 (which it probably is, since 0, 1, and 2 are opened by the shell). Because both descriptors point to the same file table entry, they share the same file status flagsread, write, append, and so onand the same current file offset.

Each descriptor has its own set of file descriptor flags. As we describe in the next section, the close-on-exec file descriptor flag for the new descriptor is always cleared by the dup functions.

Another way to duplicate a descriptor is with the fcntl function, which we describe in Section 3.14. Indeed, the call

    dup(filedes);

is equivalent to

    fcntl(filedes, F_DUPFD, 0);

Similarly, the call

    dup2(filedes, filedes2);

is equivalent to

    close(filedes2);
    fcntl(filedes, F_DUPFD, filedes2);

In this last case, the dup2 is not exactly the same as a close followed by an fcntl. The differences are as follows.

  1. dup2 is an atomic operation, whereas the alternate form involves two function calls. It is possible in the latter case to have a signal catcher called between the close and the fcntl that could modify the file descriptors. (We describe signals in Chapter 10.)

  2. There are some errno differences between dup2 and fcntl.

    The dup2 system call originated with Version 7 and propagated through the BSD releases. The fcntl method for duplicating file descriptors appeared with System III and continued with System V. SVR3.2 picked up the dup2 function, and 4.2BSD picked up the fcntl function and the F_DUPFD functionality. POSIX.1 requires both dup2 and the F_DUPFD feature of fcntl.

    Team BBL
    Previous Page Next Page