/*1* Public domain dup2() lookalike2* by Curtis Jackson @ AT&T Technologies, Burlington, NC3* electronic address: burl!rcj4*5* dup2 performs the following functions:6*7* Check to make sure that fd1 is a valid open file descriptor.8* Check to see if fd2 is already open; if so, close it.9* Duplicate fd1 onto fd2; checking to make sure fd2 is a valid fd.10* Return fd2 if all went well; return BADEXIT otherwise.11*/1213#include <errno.h>14#include <fcntl.h>15#include <unistd.h>1617#define BADEXIT -11819int20dup2(int fd1, int fd2)21{22if (fd1 != fd2) {23#ifdef F_DUPFD24if (fcntl(fd1, F_GETFL) < 0)25return BADEXIT;26if (fcntl(fd2, F_GETFL) >= 0)27close(fd2);28if (fcntl(fd1, F_DUPFD, fd2) < 0)29return BADEXIT;30#else31errno = ENOTSUP;32return BADEXIT;33#endif34}35return fd2;36}373839