Search code examples
cunixposixfile-descriptordup2

closing a file descriptor and then using it


Below is a code segment which explains dup2 system call. What I don't understand is, after duplicating both file descriptors why do we need to close the old file descriptor. Since "out" descriptor is closed now, how does a message sent to stdout_fileno gets written to "out" as well. Please note that the code wasn't written by me.

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(){

    int out;
    out=open("out",O_WRONLY | O_TRUNC | O_CREAT,S_IRUSR|S_IRGRP | S_IWGRP | S_IWUSR);

    dup2(out,STDOUT_FILENO);
    close(out); 
    printf("now this should be written to a file called out \n");
    return 0;


}

Solution

  • why do we need to close the old file descriptor

    You don't really need to; the example mainly shows that you can. However, each process on a Unix system has a limited number of file descriptors at its disposal, and when you have two of them referring to the same file, one of them is unnecessary so you might as well close it.

    Since "out" descriptor is closed now, how does a message sent to stdout_fileno gets written to "out" as well.

    Because after the dup2, STDOUT_FILENO refers to that file as well, and closing an fd does not close its clones.