dup2

Chet Ramey chet at odin.INS.CWRU.Edu
Fri Feb 8 11:24:36 AEST 1991


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 at ins.CWRU.Edu		My opinions are just those, and mine alone.



More information about the Comp.unix.wizards mailing list