xref: /minix/minix/lib/libc/sys/dup2.c (revision 7f5f010b)
1 #include <sys/cdefs.h>
2 #include "namespace.h"
3 #include <lib.h>
4 
5 #include <fcntl.h>
6 #include <unistd.h>
7 
8 int dup2(fd, fd2)
9 int fd, fd2;
10 {
11 /* The behavior of dup2 is defined by POSIX in 6.2.1.2 as almost, but not
12  * quite the same as fcntl.
13  */
14 
15   if (fd2 < 0 || fd2 > OPEN_MAX) {
16 	errno = EBADF;
17 	return(-1);
18   }
19 
20   /* Check to see if fildes is valid. */
21   if (fcntl(fd, F_GETFL) < 0) {
22 	/* 'fd' is not valid. */
23 	return(-1);
24   } else {
25 	/* 'fd' is valid. */
26 	if (fd == fd2) return(fd2);
27 	close(fd2);
28 	return(fcntl(fd, F_DUPFD, fd2));
29   }
30 }
31