微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐