dup2

Chet Ramey chet at odin.INS.CWRU.Edu
Wed Feb 13 07:51:49 AEST 1991


In article <richard.666334818 at fafnir.la.locus.com> richard at locus.com (Richard M. Mathews) writes:

>I would post what I consider to be the right answer, but I have licensing
>problems.  I can recommend taking ideas from both Gwyn and Ramey; perhaps
>one of them would be willing to post the result of such a merge.

How about this (apologies for the Gnu coding style)?  (As an aside, I do not
think that the second fcntl will ever return EINVAL, since it only returns
that error for out-of-range values (< 0 or >= getdtablesize()), and that
case is already handled explicitly.)

dup2 (fd1, fd2)
     int fd1, fd2;
{
  int saved_errno, r;

  if (fcntl (fd1, F_GETFL, 0) == -1)    /* fd1 is an invalid fd */
    return (-1);

  if (fd2 < 0 || fd2 >= getdtablesize ())	/* This could be removed. */
    {
      errno = EBADF;
      return (-1);
    }

  if (fd1 == fd2)
    return (0);

  saved_errno = errno;
  (void) close (fd2);
  r = fcntl (fd1, F_DUPFD, fd2);

  if (r >= 0)
    errno = saved_errno;
  else
    {
      if (errno == EINVAL)
	errno = EBADF;
    }

  return (r);
}

Chet
-- 
Chet Ramey				``There's just no surf in
Network Services Group			  Cleveland, U.S.A. ...''
Case Western Reserve University
chet at ins.CWRU.Edu		My opinions are just those, and mine alone.



More information about the Comp.unix.wizards mailing list