bjlockie <> wrote:
> This code never gets to 'here3'.
> I think because the command ping never finishes (ping is an example
> command, there are no switches to make the real command stop).
> I've seen similar code working elsewhere.
> my $cmd = 'ping google.ca >/dev/null |';
> open( ZAP, $cmd ) || die "can't fork: $!";
You'd nowadays better use the three-argument form of open
and variables for file handles:
my $cmd = 'ping google.ca > /dev/null';
open my $zap, '-|', $cmd or die "can't fork: $!";
> print $cmd . "\n";
> print "here2\n";
> while (my $line = <ZAP>) {
> print $line;
> }
> print "here3\n";
Yes, of course, if ping never finishes, why should the loop
terminate? If you want it to end you must decide on a condi-
tion and implement that. One possibility would be to stop
after a certain number of lines - add a counter that you
increment in the loop and use in the loop condition. Another
condition could be that you only want to read for a certain
time, this could be dealt with with by setting up a timer (e.g.
with the alarm() function) that raises the SIGALRMsignal and
kill the process in the handler for that signal (the PID of
the spawned process is what open returns). Something like
use strict;
use warnings;
my $cmd = 'ping google.ca > /dev/null';
my $pid = open my $zap, '-|', $cmd or die "can't fork: $!";
$SIG{ ALRM } = sub { kill 'TERM', $pid };
print "here2\n";
alarm 3;
while ( my $line = <$zap> ) {
print $line;
}
print "here3\n";
should do the job of getting out of the loop after 3 seconds.
Sorry, without knowing what you want to achieve it's a bit
difficult to be more specific.
Regards, Jens
--
\ Jens Thoms Toerring ___
\__________________________
http://toerring.de