blob: 2579afd443dca8453bcff75619772ed514fb3278 [file] [log] [blame]
Guido van Rossumbe0e9421993-12-24 10:32:00 +00001/*
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 <fcntl.h>
Amaury Forgeot d'Arc90774dd2010-10-05 22:15:37 +000015#include <unistd.h>
Guido van Rossumbe0e9421993-12-24 10:32:00 +000016
17#define BADEXIT -1
18
19int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000020dup2(int fd1, int fd2)
Guido van Rossumbe0e9421993-12-24 10:32:00 +000021{
22 if (fd1 != fd2) {
23 if (fcntl(fd1, F_GETFL) < 0)
24 return BADEXIT;
25 if (fcntl(fd2, F_GETFL) >= 0)
26 close(fd2);
27 if (fcntl(fd1, F_DUPFD, fd2) < 0)
28 return BADEXIT;
Guido van Rossumbe0e9421993-12-24 10:32:00 +000029 }
30 return fd2;
31}