Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Run and kill external programm after x seconds

by stevieb (Canon)
on Nov 22, 2016 at 14:51 UTC ( [id://1176341] : note . print w/replies, xml ) Need Help??


in reply to Run and kill external programm after x seconds

This works for me on both Linux and Windows (Strawberry Perl). First, we set a timeout in the $time variable, which in this example is two seconds. Then, inside of an eval, we simulate a long (relatively) running command, which is wrapped by an ALRM signal handler. If the command runs longer than the timeout (in the example, I simulate a long running command with sleep), we catch the error message caught from die, and act on it. Otherwise, we display the output of the command

Reduce the sleep to a lower number than $time (ie. zero) to get the return properly:

use warnings; use strict; my $time = 2; my $cmd = 'dir'; my $check = 1; my $output; print "check is $check\n"; eval { local $SIG{ALRM} = sub { die 'timed out'; }; alarm $time; $output = `$cmd`; sleep 4; $check++; alarm 0; }; if ($@ && $@ =~ /timed out/){ print "damn command timed out!\n"; } else { print "$output\n"; } print "check is now $check\n";

Replies are listed 'Best First'.
Re^2: Run and kill external programm after x seconds
by demichi (Beadle) on Nov 22, 2016 at 15:19 UTC
    Hi,

    thanks that works (with system() instead of backticks - for any reason I do not get dir output with backticks.

    I tried it with the CMD I would use and it does not stop after 2 seconds.

    use warnings; use strict; my $time = 2; my $cmd = 'dir'; my $check = 1; my $output; print "check is $check\n"; eval { local $SIG{ALRM} = sub { die 'timed out'; }; alarm $time; my $cmd_1 = "perl hello.pl"; # see hello.pl code below" open (CMD, "$cmd_1 2>&1|") or warn ("!!! Can't run program +: $!\n"); while (my $line = <CMD>) { print $line; } close CMD; sleep 4; $check++; alarm 0; }; if ($@ && $@ =~ /timed out/){ print "damn command timed out!\n"; } else { print "$output\n"; } print "check is now $check\n";

    hello.pl

    use strict; use warnings; $| = 1; print "Hello World\n"; print "Sleeping 1000 seconds\n"; for (1 .. 1000) { sleep 1; print ".\n"; }

    Any idea why this does not work?

    rgds de Michi