![](/img/trans.png)
[英]Why an executable running in shell output to stdout instead of stderr when crashes?
[英]Why is the output order different from the call order when using fprintf with stdout or stderr?
我的环境是 Debian GNU/Linux 11。
带有参数stdout
或stderr
的fprintf
function 给出了意外的 output 订单。
int main() {
std::cout << "Hello, World!" << std::endl;
fprintf(stderr, "22222\n");
fprintf(stdout, "111\n");
printf("3333 \n");
printf("44444 \n");
return 0;
}
我已经运行了很多次并得到了许多不同的结果:
//①
22222
Hello, World!
111
3333
44444
//②
Hello, World!
111
3333
44444
22222
什么原因? 或者,我想了解现象,需要什么知识?
据我了解,output 日志应该是这样的:
//③
Hello, World!
22222
111
3333
44444
关于①/②的两条output日志,看不懂。
我认为日志③是对的,但它没有出现,这让我感到奇怪。
output永远不会像②,因为output 到stderr
没有被缓冲,所以22222
将立即被刷新,并且会在任何其他数字之前。 Output 到stdout
可以是行缓冲的(Linux 上的默认值)或全缓冲的(Windows 上的默认值)
output 也不应该像①,因为你已经在第一行用std::endl
刷新了,因此Hello, World!
将首先打印。 这就是为什么永远不要使用std::endl
,除非你真的知道它在做什么。 始终使用std::cout << "Hello, World;\n";
. 参见“std::endl”与“\n”
③ 应该是正确的 output 因为在 Linux 上它会在每条语句上刷新,在 Windows 上,最后 3 次写入到stdout
结束时立即刷新
Hello, World!
22222
111
3333
44444
如果有任何差异,那么您的 stdlib 存在一些问题
默认情况下 ,legacy 和 C++ 流也是同步的,因此可以混合两种类型的流,但会带来一些性能损失。 你可以像这样禁用它
std::ios::sync_with_stdio(false);
为了获得更好的性能,但现在是Hello, World!
字符串可以在任何地方打印
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.