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;
}