Search code examples
linuxperlperl-io

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.


Solution

  • #!/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: $! $?";