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
myfile.txt instead of the log file. How is this possible?