Why is the STDOUT line printed after the STDERR line?

て烟熏妆下的殇ゞ 提交于 2021-01-27 07:22:23

问题


I completly don't understand this behaviour.

I have a very simple Perl script:

#!/usr/bin/perl

use strict;
use warnings;

print "line 1\n";
print STDERR "line 2\n";

If I run it from console I will get what I expect:

$ perl a.pl
line 1
line 2

But if I redirect it to file, I will get the lines in the reverse order:

$ perl a.pl &> a
$ cat a
line 2
line 1

How can I capture all the outputs STDOUT+STDERR to the file with the same order I get in the console?


回答1:


This is an effect of buffering. When outputting to a terminal, Perl (just as stdio) uses line based buffering, which will give the expected effect. When outputting to a file, it uses block buffering (typically 4k or 8k blocks), hence it will only flush on program end.

The difference you're observing is because STDERR is unbuffered, unlike most other handles.

The easiest way to circumvent this issue is to enable autoflushing on STDOUT, using the $| special variable. See perlvar for more details.




回答2:


Don't use $|, use autoflush instead.

STDOUT->autoflush(1);
STDERR->autoflush(1);

See http://perldoc.perl.org/IO/Handle.html



来源:https://stackoverflow.com/questions/17378189/why-is-the-stdout-line-printed-after-the-stderr-line

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