Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect stdout and stderr to the same file and restore it

I am redirecting the output of stderr and stdout of my c program to two files and then restoring the original stdout and stderr:

int sout = dup(fileno(stdout));
freopen("test.txt","w",stdout);

int serr = dup(fileno(stderr));
freopen("test.txt","a",stderr);

//some output....

dup2(sout,fileno(stdout));
close(sout);

dup2(serr,fileno(stderr));
close(serr);

That's the code axample. This works.

But I would like to redirect stdout and stderr to the same file(and later restore it again) so that the output is sorted in the same order as it is sorted on the console output when not redirecting stderr and stdout. How can I do that?

like image 455
unlimited101 Avatar asked Mar 01 '13 10:03

unlimited101


People also ask

Can you redirect stdout and stderr to the same file?

When saving the program's output to a file, it is quite common to redirect stderr to stdout so that you can have everything in a single file. > file redirect the stdout to file , and 2>&1 redirect the stderr to the current location of stdout . The order of redirection is important.

How do I redirect stderr and stdout to a file in Windows?

When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol. This selects the second output stream that is STDERR.


1 Answers

Instead of opening the file again for stderr,as in:

freopen("test.txt","a",stderr);

redirect it to stdout at the file descriptor level by doing:

dup2(fileno(stdout), fileno(stderr));

Note that stdout and stderr will still use independent user level buffers and, when not directed at an interactive terminal, flushing rules are different. This will most likely be the main cause for different output ordering when redirected. See this explanation of flushing modes and the man page for setvbuf().

like image 115
jop Avatar answered Oct 30 '22 13:10

jop