Operating Systems - Projects and Exercises

Duplicating an Open File Descriptor

The left arrow above will return you to the Home page
The left arrows below will return you to the Previous page

An existing file descriptor (filedes) 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. Thus by closing one of the standard file descriptors (STDIN_FILENO, STDOUT_FILENO, or STDERR_FILENO, normally 0, 1 and 2 respectively) immediately before calling dup, we can guarantee (in a single threaded environment!) that filedes will be allotted that empty number.

With dup2 we specify the value of the new descriptor with the filedes2 argument and it is an atomic call. If filedes2 is already open, it is first closed. If filedes equalsfiledes2 , then dup2 returns filedes2 without closing it.

The descriptions of the system functions above are drawn from sources that include manuals on the Sun Solaris system and the MAC OS X Darwin/BDS system, and also from 'Advanced Programming in the UNIX Environment', W. Richard Stevens, Addison-Wesley, 1993.

Go back top

For use only by students and instructors using the supplementary material available with the text book: "Operating Systems - Internals and Design Principles", William Stallings, Prentice Hall, 5th Edition, 2004. Not to be printed out or copied by any other persons or used for any other purpose without written permission of the author(s).

©