为什么在STDERR行之后打印STDOUT行? [英] Why is the STDOUT line printed after the STDERR line?

查看:59
本文介绍了为什么在STDERR行之后打印STDOUT行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全不了解这种行为.

I completly don't understand this behaviour.

我有一个非常简单的Perl脚本:

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

如何使用相同的命令将所有输出STDOUT + STDERR捕获到文件中命令我进入控制台?

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

推荐答案

这是缓冲的效果.当输出到终端时,Perl(与stdio一样)使用基于行的缓冲,这将产生预期的效果.输出到文件时,它使用块缓冲(通常为4k或8k块),因此仅在程序结束时刷新.

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.

您观察到的差异是因为STDERR是无缓冲的,与大多数其他句柄不同.

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

解决此问题的最简单方法是使用 $ | 特殊变量在STDOUT上启用自动刷新.有关更多详细信息,请参见 perlvar .

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

这篇关于为什么在STDERR行之后打印STDOUT行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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