DUP(2) | System Calls Manual | DUP(2) |
int
dup(int oldfd);
int
dup2(int oldfd, int newfd);
int
dup3(int oldfd, int newfd, int flags);
To get an independent handle with its own seek position and settings, an additional open(2) call must be issued. (This is not generally possible for pipes and sockets.)
The dup call chooses the new descriptor: it is the lowest-numbered descriptor not currently in use. The dup2 and dup3 calls allow the caller to choose the new descriptor by passing newfd, which must be within the range of valid descriptors. If newfd is the same as oldfd, the call has no effect. Otherwise, if newfd is already in use, it is closed as if close(2) had been called.
File descriptors are small non-negative integers that index into the per-process file table. Values 0, 1, and 2 have the special property that they are treated as standard input, standard output, and standard error respectively. (The constants STDIN_FILENO, STDOUT_FILENO, and STDERR_FILENO are provided as symbolic forms for these values.) The maximum value for a file descriptor is one less than the file table size. The file table size can be interrogated with getdtablesize(3) and can to some extent be adjusted with setrlimit(2).
The dup3() call includs an additional flags argument supporting a subset of the open(2) flags:
In the case of dup() and dup2() the close-on-exec flag on the new file descriptor is always left unset and all the modes and settings of the underlying object are left unchanged.
Functionality similar to dup() with slightly different semantics is also available via fcntl(2).
#include <unistd.h> int fds[2]; pid_t pid; pipe(fds); pid = fork(); if (pid == 0) { /* child; use read end of pipe to stdin */ dup2(fds[0], STDIN_FILENO); close(fds[0]); close(fds[1]); execv("/some/program", args); } /* parent process; return write end of pipe */ close(fds[0]); return fds[1];
December 24, 2013 | NetBSD 7.2 |