_dup2.c 558 B

123456789101112131415161718192021222324252627282930
  1. #include <lib.h>
  2. #define dup2 _dup2
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5. #include <limits.h>
  6. #include <errno.h>
  7. PUBLIC int dup2(fd, fd2)
  8. int fd, fd2;
  9. {
  10. /* The behavior of dup2 is defined by POSIX in 6.2.1.2 as almost, but not
  11. * quite the same as fcntl.
  12. */
  13. if (fd2 < 0 || fd2 > OPEN_MAX) {
  14. errno = EBADF;
  15. return(-1);
  16. }
  17. /* Check to see if fildes is valid. */
  18. if (fcntl(fd, F_GETFL) < 0) {
  19. /* fd is not valid. */
  20. return(-1);
  21. } else {
  22. /* fd is valid. */
  23. if (fd == fd2) return(fd2);
  24. close(fd2);
  25. return(fcntl(fd, F_DUPFD, fd2));
  26. }
  27. }