将stdout和stderr重定向到同一文件并还原 [英] Redirect stdout and stderr to the same file and restore it

查看:174
本文介绍了将stdout和stderr重定向到同一文件并还原的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将我的c程序的stderr和stdout的输出重定向到两个文件,然后还原原始的stdout和stderr:

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.

但是我想将stdout和stderr重定向到同一文件(然后再次还原),以便在不重定向stderr和stdout时,输出按与控制台输出上排序相同的顺序排序.我该怎么办?

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?

推荐答案

而不是再次为stderr打开文件,例如:

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

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

通过以下操作将其重定向到文件描述符级别的stdout:

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

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

请注意,stdoutstderr仍将使用独立的用户级别缓冲区,并且当不针对交互式终端时,刷新规则也有所不同.重定向时,这很可能是导致不同输出顺序的主要原因.请参阅有关刷新模式的说明setvbuf()的手册页.

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重定向到同一文件并还原的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆