in reply to Re: How to end a process started with open "cmd |" before it has output
in thread How to end a process started with open "cmd |" before it has output

That's actually how I started out, but it doesn't work in this case. If you try the below code, you'll notice it suffers the same problem as the code I posted before.

In this case, the alarm will fire and execute the die() statement, and the program will print out the "NONE" message, but then it will hang because the program will try to close the $fh filehandle when it exits. This will, as above, hang until some input is received.

use strict; use warnings; use IO::Select; my $an; my $timeout = 20; my $read_set = new IO::Select(); eval { local $SIG{ALRM} = sub { die "Timeout\n"; }; alarm $timeout; open my $fh, "tcpdump -nn -l -e dst 224.111.111.112 and not igmp 2>/ +dev/null |"; $read_set->add($fh); while (1) { my ($rh_set) = IO::Select->select($read_set, undef, undef, 1); if (defined $rh_set) { if ($_ = <$fh>) {; if (s/^\S* \S* M \S* \S* 0800 \S*: (\S*\.\S*\.\S*\.\S*)\.\S* > + \S*\.\S*:.*$/$1/s) { $an = $1; alarm 0; last; } } else { logwarn "EOF while reading from tcpdump. sleeping 2 seconds an +d restarting tcpdump"; $read_set->remove($fh); close $fh; sleep 2; open $fh, "tcpdump -nn -l -e dst 224.111.111.112 and not igmp +2>/dev/null |"; $read_set->add($fh); } } } close $fh; }; if ($@ && ($@ ne "Timeout\n")) { die $@; } if (defined $an) { print "$an\n"; exit 0; } else { print "NONE\n"; exit 1; }
  • Comment on Re: Re: How to end a process started with open "cmd |" before it has output
  • Download Code