in reply to Killing a system/exec/`` call if it times out

What is the form of the command? If it involves redirection, for example, perl does not directly execute the command but rather invokes the shell to do it. Thus, when you break out of the call, you are actually killing a shell invocation, not the offending process. While I hate to invoke bash-like magic, the simplest solution I have found involves actual process management and essentially grepping the results of ps. The following is code I use to handle this problem in one of my scripts: I invite criticism if someone has a better way.
my $pid = open my $calc, '-|', "$command 2>&1" or die "Pipe failed on open: $!\n"; my $vector = ''; vec($vector,fileno($calc),1) = 1; # Flip bit for pipe unless (select($vector,undef,undef,$timeout)) { # Calculation +is hanging # collect list of spawned processes my @pids = $pid; my $i = -1; push @pids, `ps --ppid $pids[$i] -o pid` =~ /\d+/g while + ++$i < @pids; kill 9, $_ for @pids; die "Calculation call failed to return with $timeout secon +ds\n"; } local $/; # Slurp my $content = <$calc>; close $calc;

Replies are listed 'Best First'.
Re^2: Killing a system/exec/`` call if it times out
by Cagao (Monk) on Dec 01, 2011 at 18:51 UTC
    Thanks, it's a simple call to a program which will hopefully create an image for me, just a program and 2 parameters, no redirection.

    Although it is doing the "sh -c ..." approach as you mentioned. I don't care how it's called either, system(), exec(), or backticks.

    I could collect the PIDs based on their parent, but would love a one-liner-ish. :)
      "I don't care how it's called either, system(), exec(), or backticks."
      Actually, yes you do (or should): see the docs for exec, taking special notes of the first paragraph:
      "The "exec" function executes a system command *and never returns*; use "system" instead of "exec" if you want it to return. It fails and returns false only if the command does not exist *and* it is executed directly instead of via your system's command shell (see below)."

      And the difference between system and backticks? sgifford put it clearly and succinctly ( in Re: system() vs `backtick`, q.v. ) back in 2004, when he said "backticks send the executed program's STDOUT to a variable, and system sends it to your main program's STDOUT."

      But, don't quit there; read similarly re system. And re backticks... well you get the idea.

        hehe, true, and I already did.

        I meant which gives me the easiest solution is fine by me. :)