Well, yes.

If you're worried about terminating the spawned program, don't use backticks. Most of the time, I don't use backticks anyway. I'd much rather do something like this:

my $cmd_pid = open my $cmd_fh, '-|', $cmd or die "Can't run '$cmd': $!\n"; my $yawn = do { local $/; <$cmd_fh> }; close $cmd_fh;

It does the same thing, and it complains about errors, and it gives me the PID of the child process, which I can use to cause the sort of interruption you're looking for:

my $start_time = time; sub exec_time { return time - $start_time } my $cmd = 'sleep 3600 ; echo "yawn"'; my $yawn; my $cmd_pid = open my $cmd_fh, '-|', $cmd or die "Can't run '$cmd': $!\n"; eval { local $SIG{ALRM} = sub { kill 15, $cmd_pid; die "alarm\n" }; alarm 5; $yawn = do { local $/; <$cmd_fh> }; alarm 0; }; close $cmd_fh; printf "(%d) yawn? $yawn", exec_time(); __END__ (5) yawn?

Note that in this case, if I don't kill the child, the program will still hang when it gets to close, because that will wait for the pipe to finish. You can put the close inside the eval, but then you have a filehandle dangling open.

Note also that if the child spawns a child (as it does in this case because the child is sh -c), then that grandchild is not killed. I don't see that there's much to do about that in any case.

Also, just for the record, this morning I'm testing on a different machine.

kyle@xxx:~$ perl -v | head -5 This is perl, v5.8.8 built for i486-linux-gnu-thread-multi Copyright 1987-2006, Larry Wall kyle@xxx:~$ uname -a Linux xxx 2.6.20-16-generic #2 SMP Thu Jun 7 20:19:32 UTC 2007 i686 GN +U/Linux

In reply to Re^9: How to timeout if a call to an external program takes too long by kyle
in thread How to timeout if a call to an external program takes too long by deivakumar

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.