linux – Perl匿名管道无输出

除非我从管道打印实际数据,否则为什么在使用匿名管道时没有打印?

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时它似乎也挂起(我认为只删除了换行符).

我觉得我遗漏了一些关于如何读取和处理管道的基本信息,但却找不到类似的问题.如果有一个然后欺骗这个,我会看看它.

需要进一步的信息.

解决方法:

改变

print "hi";

print "hi\n";

它也“工作”

它失败的原因是认情况下输出是行缓冲的

设置$|将立即冲洗缓冲区

If set to nonzero, forces a flush right away and after every write or print on the currently selected output channel. Default is 0 (regardless of whether the channel is really buffered by the system or not; “$|” tells you only whether you’ve asked Perl explicitly to flush after each write). STDOUT will typically be line buffered if output is to the terminal and block buffered otherwise. Setting this variable is useful primarily when you are outputting to a pipe or socket, such as when you are running a Perl program under rsh and want to see the output as it’s happening. This has no effect on input buffering. See the getc entry in the perlfunc manpage for that. (Mnemonic: when you want your pipes to be piping hot.)

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...