This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Populate metaconfig branch.
[metaconfig.git] / dist-3.0at70 / lib / C / fake / dup2.C
1 /*
2  * dup2.C -- A dup2 emulation.
3  */
4
5 /*
6  * $Id: dup2.C,v 3.0.1.1 1994/01/24 13:58:37 ram Exp $
7  *
8  *  Copyright (c) 1991-1993, Raphael Manfredi
9  *  
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.
15  *
16  * Original Author: Larry Wall <lwall@netlabs.com>
17  *
18  * $Log: dup2.C,v $
19  * Revision 3.0.1.1  1994/01/24  13:58:37  ram
20  * patch16: created
21  *
22  */
23
24 #include "config.h"
25
26 #ifdef I_FCNTL
27 #include <fcntl.h>
28 #endif
29
30 #include "confmagic.h"          /* Remove if not metaconfig -M */
31
32 #ifndef HAS_DUP2
33 /*
34  * dup2
35  *
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.
39  *
40  * Returns 0 if OK, -1 on failure with errno being set to indicate the error.
41  * 
42  */
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 */)
46 {
47 #ifdef HAS_FCNTL
48 #ifdef F_DUPFD
49 #define USE_FNCTL
50 #endif
51 #endif
52
53 #ifdef USE_FCNTL
54         if (old == new)
55                 return 0;
56
57         close(new);
58         return fcntl(old, F_DUPFD, new);
59 #else
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 */
63
64         if (old == new)
65                 return 0;
66
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 */
70         
71         while (fd_top > 0)                              /* Close all useless dup'ed slots */
72                 close(fd_used[--fd_top]);
73         
74         return 0;
75 #endif
76 }
77 #endif
78