8

我正在尝试从 Perl 的管道中读取未缓冲的数据。例如在下面的程序中:

open FILE,"-|","iostat -dx 10 5";
$old=select FILE;
$|=1;
select $old;
$|=1;

foreach $i (<FILE>) {
  print "GOT: $i\n";
}

iostat 每 10 秒(五次)吐出数据。你会期望这个程序做同样的事情。但是,它似乎会挂起 50 秒(即 10x5),之后它会吐出所有数据。

我怎样才能返回任何可用的数据(以无缓冲的方式),而无需一直等待 EOF?

PS 我在 Windows 下看到了很多对此的引用——我在 Linux 下这样做。

4

4 回答 4

5
#!/usr/bin/env perl

use strict;
use warnings;



open(PIPE, "iostat -dx 10 1 |")       || die "couldn't start pipe: $!";

while (my $line = <PIPE>) {
    print "Got line number $. from pipe: $line";
}

close(PIPE)                           || die "couldn't close pipe: $! $?";
于 2012-03-09T17:48:01.257 回答
1

如果可以在 Perl 脚本中等待而不是在 linux 命令上等待,这应该可以。我认为 Linux 在命令执行完成之前不会将控制权交还给 Perl 脚本。

#!/usr/bin/perl -w
my $j=0;
while($j!=5)
{
    open FILE,"-|","iostat -dx 10 1";
    $old=select FILE;
    $|=1;
    select $old;
    $|=1;

    foreach $i (<FILE>)
    {
        print "GOT: $i";
    }
    $j++;
    sleep(5);
}
于 2012-03-09T17:22:12.887 回答
1

到目前为止,解决方案在取消缓冲(Windows ActiveState Perl 5.10)方面对我不起作用。

根据http://perldoc.perl.org/PerlIO.html,“要获得无缓冲的流,请在开放调用中指定无缓冲的层(例如 :unix ):”。

所以

open(PIPE, '-|:unix', 'iostat -dx 10 1') or die "couldn't start pipe: $!";

while (my $line = <PIPE>) {
    print "Got $line";
}

close(PIPE);

这在我的情况下有效。

于 2013-02-08T20:46:54.100 回答
1

我有以下代码为我工作

#!/usr/bin/perl
use strict;
use warnings;
open FILE,"-|","iostat -dx 10 5";

while (my $old=<FILE>)
{
  print "GOT: $old\n";
}
于 2012-03-09T17:38:39.240 回答