Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!apple!agate!usenet.ins.cwru.edu!odin!chet From: chet@odin.INS.CWRU.Edu (Chet Ramey) Newsgroups: comp.unix.wizards Subject: Re: dup2 Message-ID: <1991Feb8.002436.21328@usenet.ins.cwru.edu> Date: 8 Feb 91 00:24:36 GMT References: <27B1CA1C.22559@ics.uci.edu> Sender: news@usenet.ins.cwru.edu Reply-To: chet@po.CWRU.Edu Distribution: usa Organization: Case Western Reserve Univ. Cleveland, Ohio, (USA) Lines: 46 Nntp-Posting-Host: odin.ins.cwru.edu Doug Schmidt writes: > I'm curious, is it possible to implement the dup2() system >call using only routines available in the standard C library and other >existing system calls? When you really get down to it. the kernel is going to have to do the nitty-gritty duplication for you, otherwise it gets tricky. If you have an fcntl(..., F_DUPFD, ...), it's straightforward. Here's how we do it in bash: dup2 (fd1, fd2) int fd1, fd2; { if (fcntl (fd1, F_GETFL, 0) == -1) /* fd1 is an invalid fd */ return (-1); if (fd2 < 0 || fd2 >= getdtablesize ()) { errno = EBADF; return (-1); } if (fd1 == fd2) return (0); (void) close (fd2); return (fcntl (fd1, F_DUPFD, fd2)); } (getdtablesize() can be replaced with: sysconf(_SC_OPEN_MAX) Posix ulimit(4, 0L) System V.3 and up NOFILE just about anything else and of course the value can be fetched once into a static variable and cached.) 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.