missing/dup2.c


DEFINITIONS

This source file includes following functions.
  1. dup2


   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 "config.h"
  15  
  16  #if defined(HAVE_FCNTL)
  17  # include <fcntl.h>
  18  #endif
  19  
  20  #if !defined(HAVE_FCNTL) || !defined(F_DUPFD)
  21  # include <errno.h>
  22  #endif
  23  
  24  #define BADEXIT -1
  25  
  26  int
  27  dup2(fd1, fd2)
  28  int fd1, fd2;
  29  {
  30  #if defined(HAVE_FCNTL) && defined(F_DUPFD)
  31          if (fd1 != fd2) {
  32  #ifdef F_GETFL
  33                  if (fcntl(fd1, F_GETFL) < 0)
  34                          return BADEXIT;
  35                  if (fcntl(fd2, F_GETFL) >= 0)
  36                          close(fd2);
  37  #else
  38                  close(fd2);
  39  #endif
  40                  if (fcntl(fd1, F_DUPFD, fd2) < 0)
  41                          return BADEXIT;
  42          }
  43          return fd2;
  44  #else
  45          extern int errno;
  46          int i, fd, fds[256];
  47  
  48          if (fd1 == fd2) return 0;
  49          close(fd2);
  50          for (i=0; i<256; i++) {
  51                  fd = fds[i] = dup(fd1);
  52                  if (fd == fd2) break;
  53          }
  54          while (i) {
  55                  close(fds[i--]);
  56          }
  57          if (fd == fd2) return 0;
  58          errno = EMFILE;
  59          return BADEXIT;
  60  #endif
  61  }