dup2

Root Boy Jim rbj at uunet.UU.NET
Fri Feb 8 20:46:24 AEST 1991


In article <1991Feb8.002436.21328 at usenet.ins.cwru.edu> chet at 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 <rbj at uunet.uu.net>
	I got a head full of ideas
	They're driving me insane



More information about the Comp.unix.internals mailing list