Question

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?

Was it helpful?

Solution

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 call dup2(1,1) (which is a noop).

You can dup stdout into a new descriptor, keep it and redirect back to it when you want:

int oldstdout = dup(1);
....
dup2(oldstdout,1);
close(oldstdout);

OTHER TIPS

Once you've dupped over STDOUT you have lost the initial stdout file handle. You would need use dup to make a copy of your original stdout so you could dup2 to restore it. Also checking the return value of open and dup is a good idea.

The first call, dup2(myfd, 1) closes the original stdout file descriptor. The second call dup2(1, 1) is actually a no-op. If you want to be able to restore the original stdout you first have to save it and restore it afterwards. For example:

int main ()
{
  printf ("dup2 example!\n");
  int myfd= creat ( "./etest.txt", 777);
  int fd_save = dup(1):
  dup2(myfd, 1);
  printf("i am in output file!\n" );

  dup2(fd_save,1);
  close(fd_save);
  printf("i am in STDOUT!" );
  return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top