简体   繁体   English

Perl STDOUT重定向到管道,调用sleep()后没有输出

[英]Perl STDOUT redirected to a pipe, no output after calling sleep()

I'm having problems with Perl on Windows (both ActivePerl and Strawberry), when redirecting a script STDOUT to a pipe, and using sleep(). 我在使用Windows上的Perl(ActivePerl和Strawberry)时遇到问题,将脚本STDOUT重定向到管道,并使用sleep()。 Try this: 试试这个:

perl -e "for (;;) { print 'Printing line ', $i++, \"\n\"; sleep(1); }"

This works as expected. 这按预期工作。 Now pipe it to Tee (or some file, same result): 现在将它传递给Tee(或一些文件,相同的结果):

perl -e "for (;;) { print 'Printing line ', $i++, \"\n\"; sleep(1); }" | tee

There's no output at all, tee captures nothing. 根本没有输出,发球没什么。 However, the perl script is still running, only there's nothing on STDOUT until the script finishes, and then all output is dumped to tee. 但是,perl脚本仍在运行,只有在脚本完成之前STDOUT上没有任何内容,然后所有输出都被转储到tee。 Except, if the STDOUT buffer fills the script might hang. 除非,如果STDOUT缓冲区填充脚本可能会挂起。

Now, if you remove the sleep(call), the pipe works as expected! 现在,如果你删除睡眠(调用),管道按预期工作! What's going on? 这是怎么回事?

I found a workaround; 我找到了一个解决方法; disabling the STDOUT buffering with $|=1 makes the pipe work when using the sleep, but... why? 使用$ | = 1禁用STDOUT缓冲会使管道在使用睡眠时工作,但是......为什么? Can anyone explain and offer a better solution? 谁能解释并提供更好的解决方案?

You are suffering from buffering. 你正在遭受缓冲。 Add $| = 1; 添加$| = 1; $| = 1; to unbuffer STDOUT. 去缓冲STDOUT。

All file handles except STDERR are buffered by default, but STDOUT uses a minimal form of buffering (flushed by newlines) when connected to a terminal. 默认情况下,除STDERR之外的所有文件句柄都是缓冲的,但是当连接到终端时,STDOUT使用最小形式的缓冲(由换行符刷新)。 By substituting the terminal for a pipe, normal buffering is reinstated. 通过用终端代替管道,恢复正常缓冲。

Removing the sleep call doesn't change anything except to speeds things up. 删除sleep呼叫不会改变任何事情,除非加快速度。 Instead of taking minutes to fill up the buffer, it takes milliseconds. 而不是花费几分钟来填充缓冲区,它需要几毫秒。 With or without it, the output is still written in 4k or 8k blocks (depending on your version of Perl). 无论有没有,输出仍然以4k或8k块写入(取决于您的Perl版本)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM