linux - Perl anonymous pipe no output -
question
why nothing printed when using anonymous pipe, unless print actual data pipe ?
example
use strict; use warnings; $child_process_id = 0; $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: $! $?";
appears hang
use strict; use warnings; $child_process_id = 0; $vmstat_command = 'vmstat 7|'; $child_process_id = open(vmstat, $vmstat_command) || die "error when executing \"$vmstat_command\": $!"; while (<vmstat>) { print "hi" . $_ ; # ^^^ added } close vmstat or die "bad command: $! $?";
prints
hiprocs -----------memory---------- ---swap-- -----io---- -system-- -----cpu------ hi r b swpd free buff cache si bi bo in cs sy id wa st hi 1 0 0 7264836 144200 307076 0 0 0 1 0 14 0 0 100 0 0
etc...
expected behaviour
would print hi every line of output of vmstat first example.
versions
perl, v5.10.0 gnu bash, version 3.2.51
misc
it appears hang when using chomp before printing line (which thought removes newlines).
i feel i'm missing fundamental how pipe read , processed not find similar question. if there 1 dupe , i'll have @ it.
any further information needed ask.
alter
print "hi";
to
print "hi\n";
and "works"
the reason fails output line buffered default
setting $|
flush buffer straight away
if set nonzero, forces flush right away , after every write or print on selected output channel. default 0 (regardless of whether channel buffered system or not; "$|" tells whether you've asked perl explicitly flush after each write). stdout typically line buffered if output terminal , block buffered otherwise. setting variable useful when outputting pipe or socket, such when running perl program under rsh , want see output it's happening. has no effect on input buffering. see getc entry in perlfunc manpage that. (mnemonic: when want pipes piping hot.)
Comments
Post a Comment