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

Is there a simple way to time out a backquoted program? After about 10 seconds I'd like to move on from the backquotes to the nextline. If this can be done, is any of the output from the running program returned? Does the program terminate or continue running until the perl script ends?
`perl -e 'while(1){};'`; print "never see this text\n";


Replies are listed 'Best First'.
Re: Timing out backquoted executions
by Trizor (Pilgrim) on Aug 02, 2007 at 19:51 UTC

    You want an alarm, however with backticks this does leave the process hanging and there's no easy way to get its pid, but it is your child so you can do things to your process group to take it down, perhaps an END that sigkills the process group?

    eval { local $SIG{ALRM} = sub { die "Alarma" }; alarm 10; `perl -e 'while(1) {};'`; alarm 0; }; if ($@ eq 'Alarma') { warn "alarm'd"; } elsif ($@) { die $@; }
      Thanks guys. Now I'm noticing though that when I do this, the process continues running. How can I be sure to terminate this process?

      > cat perl.pl #!/usr/bin/perl eval { $SIG{ALRM} = sub { die "Timed out\n"; }; alarm(5); `perl -e 'while(1){sleep 1;}'`; alarm(0); }; print "Died with: $@\n"; > ./perl.pl Died with: Timed out > ps PID TTY TIME CMD 11551 pts/0 00:00:00 bash 11648 pts/0 00:00:00 perl 11651 pts/0 00:00:00 ps
Re: Timing out backquoted executions
by liverpole (Monsignor) on Aug 02, 2007 at 19:56 UTC
    You can use alarm.  For your purposes, I'm assuming the result would look like this:
    use strict; use warnings; my $timeout = 3; eval { local $SIG{ALRM} = sub { die "alarm\n" }; alarm $timeout; `perl -e "while(1) { }"`; alarm 0; }; if ($@) { die "DID timeout after $timeout second(s)\n"; } print "never see this text\n";

    s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
Re: Timing out backquoted executions
by eyepopslikeamosquito (Archbishop) on Aug 03, 2007 at 11:26 UTC

    No simple portable way. I've done this on both Unix and Windows and chose a different technique on each. Reading the responses to Threads or no Threads should prove useful: there are a couple of nice ideas from ikegami along with links to the Unix and Windows solutions I wrote.