Question

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;


}
Was it helpful?

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.

OTHER TIPS

If you have two descriptors pointing to the same file, writing to both would cause the output to be randomly mixed; but there's no error that you can detect (i.e. the write will succeed) to tell that anything is wrong.

If you check return values, you can easily detect attempts to write to a closed file descriptor, so it's better to close the one your not using, rather than keep it around and be careful to never touch it.

stdout, stdin, stderr, are all files in *nix systems. You can think of your code as taking a "pointer" to the file out, and setting stdout, to point to this file. At that point, the first "pointer" can be removed. This is also why it uses prinft(); rather than fprintf();

You don't need to close the old file descriptor, but the code is probably meant as an example showing that you can.

As both other answers said, in general, it's probably better practice to only have one file descriptor open, as it both reduces the amount of resources used by your program and makes it easier to see that you are working with the same file. (eg. you could have a problem writing to and reading from that file in a loop)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top