Redirect stdout and stderr to the same file and restore it

有些话、适合烂在心里 提交于 2019-11-29 11:39:09

问题


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?


回答1:


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().



来源:https://stackoverflow.com/questions/15155314/redirect-stdout-and-stderr-to-the-same-file-and-restore-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!