xref: /third_party/python/Python/dup2.c (revision 7db96d56)
1/*
2 * Public domain dup2() lookalike
3 * by Curtis Jackson @ AT&T Technologies, Burlington, NC
4 * electronic address:  burl!rcj
5 *
6 * dup2 performs the following functions:
7 *
8 * Check to make sure that fd1 is a valid open file descriptor.
9 * Check to see if fd2 is already open; if so, close it.
10 * Duplicate fd1 onto fd2; checking to make sure fd2 is a valid fd.
11 * Return fd2 if all went well; return BADEXIT otherwise.
12 */
13
14#include <errno.h>
15#include <fcntl.h>
16#include <unistd.h>
17
18#define BADEXIT -1
19
20int
21dup2(int fd1, int fd2)
22{
23    if (fd1 != fd2) {
24#ifdef F_DUPFD
25        if (fcntl(fd1, F_GETFL) < 0)
26            return BADEXIT;
27        if (fcntl(fd2, F_GETFL) >= 0)
28            close(fd2);
29        if (fcntl(fd1, F_DUPFD, fd2) < 0)
30            return BADEXIT;
31#else
32        errno = ENOTSUP;
33        return BADEXIT;
34#endif
35    }
36    return fd2;
37}
38