Xref: utzoo comp.unix.wizards:24059 comp.unix.internals:2016 comp.lang.perl:3964 Path: utzoo!mnetor!tmsoft!torsqnt!lethe!yunexus!ists!helios.physics.utoronto.ca!news-server.csri.toronto.edu!cs.utexas.edu!uunet!rbj From: rbj@uunet.UU.NET (Root Boy Jim) Newsgroups: comp.unix.wizards,comp.unix.internals,comp.lang.perl Subject: Re: dup2 Message-ID: <121729@uunet.UU.NET> Date: 8 Feb 91 09:46:24 GMT References: <27B1CA1C.22559@ics.uci.edu> <1991Feb8.002436.21328@usenet.ins.cwru.edu> Followup-To: comp.unix.wizards Organization: UUNET Communications Services, Falls Church, VA Lines: 52 Cc: rbj In article <1991Feb8.002436.21328@usenet.ins.cwru.edu> chet@po.CWRU.Edu writes: >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: [You may see this twice. Sorry if you do] Well, a clear case of two left feet not knowing what the right hand is doing. The solution is trivial once you grasp the recursive nature of it. I was gonna tell y'all to look in ~emacs/src/sysdep.c, but the version there is broken! I feel like a fool, as I sent it off to Larry Wall. Dup and dup2 can fail, altho people treat it as if it can't. I just debugged the following routine. Appended is a test driver. dup2(old,new) { #ifdef F_DUPFD close(new); return(fcntl(old, F_DUPFD, new)); #else register int fd, ret; close(new); fd = dup(old); if (fd == -1) return(-1); if (fd == new) return(new); ret = dup2(old,new); close(fd); return(ret); #endif } main(c,v) char *v[]; { register int a,b; (c > 2) || (printf("usage: %s srcfd dstfd\n",v[0]),exit(1)); a = atoi(v[1]); b = atoi(v[2]); printf("dup2(%d,%d) = %d\n",a,b,dup2(a,b)); } -- Root Boy Jim Cottrell I got a head full of ideas They're driving me insane