/* dup2.c (emx+gcc) -- Copyright (c) 1992-1996 by Eberhard Mattes */

#include <io.h>
#include <errno.h>
#include <emx/io.h>
#include <emx/syscalls.h>

int _dup2 (int handle1, int handle2)
{
  int *pflags1, *pflags2, *pla1, *pla2;

  if ((pflags1 = _fd_flags (handle1)) == NULL
      || (pla1 = _fd_lookahead (handle1)) == NULL
      || handle2 < 0)
    {
      errno = EBADF;
      return -1;
    }
  /* TODO: Block signals */
  if (__dup2 (handle1, handle2) < 0)
    return -1;

  if ((pflags2 = _fd_init (handle2)) == NULL
      || (pla2 = _fd_lookahead (handle2)) == NULL)
    {
      /* TODO: Unfortunately, the original HANDLE2, if there was one,
         is now closed. */
      __close (handle2);
      errno = EMFILE;
      return -1;
    }

  *pflags2 = *pflags1;
  *pla2 = *pla1;
  return handle2;
}
