#ifdef __DJGPP__

#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <sys/stat.h>
#include <libc/environ.h>
#include "dosutil.h"

int
pipe (int fds[2])
{
  int ifd;
  int ofd;
  static char tmp_template[PATH_MAX + 1];
  static char temp_name[PATH_MAX + 1];
  static unsigned environ_changed = 0;
  char *tname;

  if (environ_changed != __environ_changed)
  {
    _fixpath ("/dev/env/TMPDIR/ppXXXXXX", tmp_template);
    environ_changed = __environ_changed;
  }

  strcpy (temp_name, tmp_template);
  tname = mktemp (temp_name);
  if (tname == NULL)
    return -1;

  ofd = _opentmp(tname, O_RDWR | O_CREAT | O_TRUNC, S_IWUSR);
  if (ofd < 0)
  {
    free (tname);
    return -1;
  }

  /* Move the handle up so it doesn't count against the 20 handle
     inherit limit.  */
  if (ofd < 20)
  {
    int tfd;

    tfd = fcntl (ofd, F_DUPFD, 20);
    close (ofd);
    if (tfd < 0)
    {
      remove (tname);
      return -1;
    }
    ofd = tfd;
  }

  /* Move this handle up too.  */
  ifd = fcntl (ofd, F_DUPFD, 20);
  if (ifd < 0)
  {
    close (ofd);
    remove (tname);
    return -1;
  }

  fds[0] = ifd;
  fds[1] = ofd;

  return 0;
}
#endif

