Reading Unbuffered Channel Data in Perl

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

open FILE,"-|","iostat -dx 10 5"; $old=select FILE; $|=1; select $old; $|=1; foreach $i (<FILE>) { print "GOT: $i\n"; } 

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

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

PS I have seen numerous links to this under Windows - I do this under Linux.

+7
source share
4 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: $! $?"; 
+5
source

If in the Perl command the script waits normally on the linux command line, this should work. I do not think that Linux will return control to the Perl script until the command completes.

 #!/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); } 
+1
source

I have below code that works for me

 #!/usr/bin/perl use strict; use warnings; open FILE,"-|","iostat -dx 10 5"; while (my $old=<FILE>) { print "GOT: $old\n"; } 
+1
source

The solutions so far have not worked for me regarding non-buffering (Windows ActiveState Perl 5.10).

According to http://perldoc.perl.org/PerlIO.html , "To get an unbuffered stream, specify an open buffer (ex: unix) in an open call:".

So,

 open(PIPE, '-|:unix', 'iostat -dx 10 1') or die "couldn't start pipe: $!"; while (my $line = <PIPE>) { print "Got $line"; } close(PIPE); 

which worked in my case.

+1
source

All Articles