leonidlm has asked for the wisdom of the Perl Monks concerning the following question:

Hi All,
Just a small question. I am using the following code:
eval { local $SIG{ALRM} = sub {die "Cant get node's time ($host)\n"}; alarm 5; @out = qx {$cmd}; if ($out[1] !~ /OVO Managed Node status :/) { print "Detected error for node $host\n"; } alarm 0; };
My problem is that if in one iteration the timeout really worked the process run by qx is still will be running in the background! Is there a way of killing this process too right after the eval will finish?

Replies are listed 'Best First'.
Re: eval leaving processess behind
by ikegami (Patriarch) on Nov 09, 2008 at 17:07 UTC
    my $cmd = ...; my $pid; my $fh; my @out; eval { local $SIG{ALRM} = sub { die "Timeout\n" }; alarm 5; $pid = open($fh, '-|', $cmd) or die; @out = <$fh>; undef $fh; alarm 0; }; kill TERM => $pid if defined($fh);
      Very nice, thank you.
      But is there a more "elegant way" of doing this ? In your solution I will fork another perl instance for each task, I am not sure it is the most efficient solution.

        q{perl -e'sleep 60*60'} was just the command I used for testing. You'd continue to use the same command as before. I've altered the post execute $cmd as your snippet did.