stdout redirection does not work if stdout is a file
c, io-redirection, posix, stdout
Solution
You need to do `fflush(stdout)` before you restore the original stdout with `dup2`.
The reason it works with a terminal is because stdout is line buffered for a terminal. So your output gets flushed immediately to the redirected file. But when you start your program with stdout to a file, stdout becomes fully buffered, so your `func` output will be in a buffer waiting to be flushed. When you restore the original stdout without flushing, the output gets written to the original stdout when the program exits.
Problem
I am using code like the following to redirect stdout before calling a noisy function from an external library written in Fortran: ``` // copy standard output out = dup(STDOUT_FILENO); // close standard output close(STDOUT_FILENO); // use log file as standard output log = open(log_file, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); if(log != STDOUT_FILENO) fprintf(stderr, "could not create log file %s", log_file); // call the library function that uses a lot of printf func(); // restore original standard output dup2(out, STDOUT_FILENO); // close copy of standard output close(out); ``` To summarise my intention of the above code snippet: copy stdout, close stdout (frees file descriptor 0), open file (uses lowest file descriptor = 0 = stdout), run code with redirected stdout, and reset stdout. This works perfectly well when I run my code using the terminal as stdout. However, when I set stdout to a file (using `$ mycode > myfile.txt`) the redirection fails, and I end up with the output of `func()` in `myfile.txt` instead of the log file. How is this possible?