dup2

Paul Falstad pfalstad at phoenix.Princeton.EDU
Fri Feb 8 09:16:32 AEST 1991


schmidt at ics.uci.edu (Doug Schmidt) wrote:
>  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?

Two ways, at least.

1: close and dup only

int dup2(int fd1,int fd2)
{
   close(fd2);
   fd1 = dup(fd1);
   if (fd1 != fd2)
      fd1 = movefd(fd1,fd2);
   return fd1;
}

int movefd(int fd1,int fd2)
{
int fe;

   if (fd1 == -1)
      return -1;
   if ((fe = dup(fd1)) != fd2)
      fe = movefd(fe);
   close(fd1);
   return fe;
}

2: fcntl

int dup2(int fd1,int fd2)
{
   close(fd2);
   return(fcntl(fd1,F_DUPFD,fd2));
}

--
Paul Falstad, pfalstad at phoenix.princeton.edu PLink:HYPNOS GEnie:P.FALSTAD
10 PRINT "PRINCETON CS"          | #include <std.disclaimer.h>
20 GOTO 10                       | [Your blood pressure just went up.]
Princeton University would like to apologize to everyone for this article.



More information about the Comp.unix.wizards mailing list