【问题标题】:Perl anonymous pipe no outputPerl匿名管道没有输出
【发布时间】:2016-01-28 10:37:12
【问题描述】:

问题

为什么在使用匿名管道时什么都不打印,除非我从管道打印实际数据?


示例

use strict;
use warnings;

my $child_process_id = 0;
my $vmstat_command = 'vmstat 7|';
$child_process_id = open(VMSTAT, $vmstat_command) || die "Error when executing \"$vmstat_command\": $!";


while (<VMSTAT>) {
    print "hi" ;
}
close VMSTAT or die "bad command: $! $?";

似乎挂起


use strict;
use warnings;

my $child_process_id = 0;
my $vmstat_command = 'vmstat 7|';
$child_process_id = open(VMSTAT, $vmstat_command) || die "Error when executing \"$vmstat_command\": $!";


while (<VMSTAT>) {
    print "hi" . $_ ;
#                ^^^ Added this
}
close VMSTAT or die "bad command: $! $?";

打印

hiprocs -----------memory---------- ---swap-- -----io---- -system-- -----cpu------
hi r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
hi 1  0      0 7264836 144200 307076    0    0     0     1    0   14  0  0 100  0  0

等等……


预期行为

对于第一个示例,将为 vmstat 的每一行输出打印 hi。


版本

perl, v5.10.0
GNU bash, version 3.2.51

杂项

在打印该行之前使用 chomp 时,它似乎也会挂起(我认为这只会删除换行符)。

我觉得我缺少有关如何读取和处理管道的基本内容,但找不到类似的问题。如果有,那就骗这个,我去看看。


如果需要任何进一步的信息,请询问。

【问题讨论】:

    标签: linux bash perl


    【解决方案1】:

    改变

    print "hi";
    

    print "hi\n";
    

    它也“有效”

    失败的原因是输出默认是行缓冲的

    设置$| 将立即刷新缓冲区

    如果设置为非零,则在当前选定的输出通道上每次写入或打印后立即强制刷新。默认值为 0(无论通道是否真正被系统缓冲;“$|”只告诉您是否明确要求 Perl 在每次写入后刷新)。如果输出到终端,则 STDOUT 通常会被行缓冲,否则会被块缓冲。设置此变量主要在您输出到管道或套接字时很有用,例如当您在 rsh 下运行 Perl 程序并希望看到正在发生的输出时。这对输入缓冲没有影响。请参阅 perlfunc 手册页中的 getc 条目。 (助记:当你想让你的管道滚烫时。)

    【讨论】:

      猜你喜欢
      • 2019-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-08
      • 2012-07-04
      • 1970-01-01
      相关资源
      最近更新 更多