in the code below
int main ()
{
printf ("dup2 example!\n");
int myfd= creat ( "./etest.txt", 777);
dup2(myfd, 1);
printf("i am in output file!\n" );
dup2(1,1);
printf("i am in STDOUT!" );
return 0;
}
i have two dup2 calls. the first one redirects the o/p from stdout to my file. this works fine. then i want to redirect it to go back again to stoud but the second dup2 does not change it and “i am in STDOUT!” is printed in the file. whats wrong with my code?
After
dup2(myfd,1);, file descriptor 1 doesn’t refer to the original standard output any more. There is no hidden place where the kernel may look for a “true” stdout when you calldup2(1,1)(which is a noop).You can
dupstdout into a new descriptor, keep it and redirect back to it when you want: