I am redirecting the output of stderr and stdout of my c program to two files and then restoring the original stdout and stderr:
我将我的c程序的stderr和stdout的输出重定向到两个文件,然后恢复原始的stdout和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?
但是我想将stdout和stderr重定向到同一个文件(以后再恢复它),以便输出按照与不重定向stderr和stdout时在控制台输出上排序的顺序相同的顺序排序。我怎样才能做到这一点?
1 个解决方案
#1
13
Instead of opening the file again for stderr
,as in:
而不是为stderr再次打开文件,如:
freopen("test.txt","a",stderr);
redirect it to stdout
at the file descriptor level by doing:
通过执行以下操作将其重定向到文件描述符级别的stdout:
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()
.
请注意,stdout和stderr仍将使用独立的用户级缓冲区,并且当不指向交互式终端时,刷新规则是不同的。这很可能是重定向时输出顺序不同的主要原因。请参阅刷新模式的说明和setvbuf()的手册页。
#1
13
Instead of opening the file again for stderr
,as in:
而不是为stderr再次打开文件,如:
freopen("test.txt","a",stderr);
redirect it to stdout
at the file descriptor level by doing:
通过执行以下操作将其重定向到文件描述符级别的stdout:
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()
.
请注意,stdout和stderr仍将使用独立的用户级缓冲区,并且当不指向交互式终端时,刷新规则是不同的。这很可能是重定向时输出顺序不同的主要原因。请参阅刷新模式的说明和setvbuf()的手册页。