2 * dup2.C -- A dup2 emulation.
6 * $Id: dup2.C,v 3.0.1.1 1994/01/24 13:58:37 ram Exp $
8 * Copyright (c) 1991-1993, Raphael Manfredi
10 * You may redistribute only under the terms of the Artistic Licence,
11 * as specified in the README file that comes with the distribution.
12 * You may reuse parts of this distribution only within the terms of
13 * that same Artistic Licence; a copy of which may be found at the root
14 * of the source tree for dist 3.0.
16 * Original Author: Larry Wall <lwall@netlabs.com>
19 * Revision 3.0.1.1 1994/01/24 13:58:37 ram
30 #include "confmagic.h" /* Remove if not metaconfig -M */
36 * This routine duplicates file descriptor 'old' into 'new'. After the
37 * operation, both 'new' and 'old' refer to the same file 'old' was referring
38 * to in the first place.
40 * Returns 0 if OK, -1 on failure with errno being set to indicate the error.
43 V_FUNC(int dup2, (old, new),
44 int old /* Opened file descriptor */ NXT_ARG
45 int new /* File descriptor we'd like to get */)
58 return fcntl(old, F_DUPFD, new);
60 int fd_used[256]; /* Fixed stack used to record dup'ed files */
61 int fd_top = 0; /* Top in the fixed stack */
62 int fd; /* Currently dup'ed file descriptor */
67 close(new); /* Ensure one free slot */
68 while ((fd = dup(old)) != new) /* Until dup'ed file matches */
69 fd_used[fd_top++] = fd; /* Remember we have to close it later */
71 while (fd_top > 0) /* Close all useless dup'ed slots */
72 close(fd_used[--fd_top]);