2

I'm implementing dup and dup2 using fcntl, that what I have coded :

int dup(int oldfd) {
    return fcntl(oldfd, F_DUPFD, STDERR_FILENO);
}

int dup2(int oldfd, int newfd) {

    if(oldfd == newfd)
        return oldfd;

    if(fcntl(oldfd, F_GETFD) == -1)
        return -1;

    if(close(newfd) == -1 && errno != EBADF)
        return -1;

    fcntl(oldfd, F_DUPFD, newfd);

    return newfd;
}

But I see that the dup2 is not efficient at all(too much system call ==> too much kernel mode switch) and dup2 is not thread safe that me that a race condition can happen, because if between the close(newfd) and fcntl(oldfd, F_DUPFD, newfd) another thread take the control and open a file the file descriptor newfd will maybe be taken.

So how to make dup2 more efficient and thread-safe ?

Ganapathy
  • 545
  • 1
  • 6
  • 23
KarimS
  • 3,812
  • 9
  • 41
  • 64

0 Answers0