I am working with a multi-thread program.
First I redirect my stdout to a certain file. No problem there (I used dup2(fd, 1)
where fd
is t
If the program runs on a Linux environment, you can freopen ("/dev/stdout", "a", stdout)
.
But if you know that stdout
was the terminal, freopen ("/dev/tty", "a", stdout)
or the equivalent for other OSs—even Windows.
#include <unistd.h>
...
int saved_stdout;
...
/* Save current stdout for use later */
saved_stdout = dup(1);
dup2(my_temporary_stdout_fd, 1);
... do some work on your new stdout ...
/* Restore stdout */
dup2(saved_stdout, 1);
close(saved_stdout);
Before you do the dup2(fd, STDOUT_FILENO)
, you should save the current open file descriptor for standard output by doing int saved_stdout = dup(STDOUT_FILENO);
(letting dup() choose an available file descriptor number for you). Then, after you've finished with the output redirected to a file, you can do dup2(saved_stdout, STDOUT_FILENO)
to restore standard output to where it was before you started all this (and you should close saved_stdout
too).
You do need to worry about flushing standard I/O streams (fflush(stdout)
) at appropriate times as you mess around with this. That means 'before you switch stdout over'.