Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read unbuffered data from pipe in Perl

I am trying to read unbufferd data from a pipe in Perl. For example in the program below:

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

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

iostat spits out data every 10 seconds (five times). You would expect this program to do the same. However, instead it appears to hang for 50 seconds (i.e. 10x5), after which it spits out all the data.

How can I get the to return whatever data is available (in an unbuffered manner), without waiting all the way for EOF?

P.S. I have seen numerous references to this under Windows - I am doing this under Linux.

like image 473
Brad Avatar asked Mar 09 '12 15:03

Brad


2 Answers

#!/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: $! $?";
like image 78
tchrist Avatar answered Oct 05 '22 14:10

tchrist


If it is fine to wait in your Perl script instead on the linux command, this should work. I don't think Linux will give control back to the Perl script before the command execution is completed.

#!/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);
}
like image 27
Jean Avatar answered Oct 05 '22 15:10

Jean