Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!hellgate.utah.edu!caen!zaphod.mps.ohio-state.edu!ncar!gatech!usenet.ins.cwru.edu!odin!chet From: chet@odin.INS.CWRU.Edu (Chet Ramey) Newsgroups: comp.unix.wizards Subject: Re: dup2 Message-ID: <1991Feb12.205149.22245@usenet.ins.cwru.edu> Date: 12 Feb 91 20:51:49 GMT References: <27B1CA1C.22559@ics.uci.edu> <15136@smoke.brl.mil> Sender: news@usenet.ins.cwru.edu Reply-To: chet@po.CWRU.Edu Organization: Case Western Reserve Univ. Cleveland, Ohio, (USA) Lines: 50 Nntp-Posting-Host: odin.ins.cwru.edu In article richard@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@ins.CWRU.Edu My opinions are just those, and mine alone.