my-server
← Wiki

Dup (system call)

In Unix-like operating systems, (short for "duplicate") and system calls create a copy of a given file descriptor. This new descriptor actually does not behave like a copy, but like an alias of the old one.

C library POSIX definition

The and calls are standardized by the POSIX specification. Similar(following the logic) to pointers, the new file description is merely an alias to the old one, with both file descriptors being capable of being used interchangeably. Both file descriptors in a system call refer to the same open file description which means they share file offset and file status flags; Similar but not identical to the logic used in pointers, shallow or deep copying or references, changes to the offset on one of the file descriptors changes it for the other file descriptor. When using , the two file descriptors don't share the same file descriptor flags. In the calling process the lowest numbered unused file descriptor will be used for the new file descriptor number. When using the system call it performs the same task as with the exception of using the file descriptor number specified in the variable of the call, in that is adjusted to refer to the file description. The last system call in this family of functions is , which is the same as except that if equals the system call fails with error and the caller can force the close-on-exec flag to be set by specifying in flags. dup3() was formally added to Linux kernel version 2.6.27 (glibc support is available on version 2.9 and above).

The former allocates the first available descriptor, just like behaves; an alternative way to duplicate a file descriptor to an unspecified place is the system call with <code>F_DUPFD</code> command.

The latter places the copy into . If is open, it is closed first.

dup2 for input/output redirection

Unix shells use for input/output redirection. Along with <code>pipe()</code>, it is a tool on which Unix pipes rely.

The following example uses <code>pipe()</code> and <code>dup()</code> in order to connect two separate processes (' and ') using Unix pipes:

See also

  • File descriptor&nbsp;– how it works and other functions related to open

References

  • Advanced Programming in the UNIX Environment by W. Richard Stevens