Try this.
eval { local $SIG{'ALRM'} = sub { die "timed out\n" }; alarm(10); system("sleep 30; echo 'I made it'") && die "system call faile +d\n"; alarm(0); }; if ($@) { if ($@ eq "timed out\n") { print "I timed out\n"; } else { print "something else went boom\n"; } } else { print "I didn't time out\n"; }
In ten seconds you should get output that reads "I timed out". This is almost exactly the eval timeout out example from the 'perlfunc' perldoc page. I modified it a little to have print statements for what happened where.

/\/\averick

Updated:

bluto is quite right. here is my updated code. This seems to work fine under Linux. The only problem I have with Dominus solution is requiring the external program (you should be able to get it to work in one piece of code IMHO ;) )

-- first.pl -- #!/usr/bin/perl use strict; my $pid; eval { local $SIG{'ALRM'} = sub { die "timed out\n" }; alarm(10); $pid = fork; if ($pid == 0) { exec("./second.pl"); } else { wait; } alarm(0); }; if ($@) { if ($@ eq "timed out\n") { kill(15,$pid); print "I timed out\n"; } else { print "something else went boom\n"; } } else { print "I didn't time out\n"; } -- second.pl -- #!/usr/bin/perl while(1) { print "alive\n"; sleep(1); }
This produces this output on my system.
darkstar:~>./first.pl alive alive alive alive alive alive alive alive alive alive I timed out darkstar:~>

In reply to Re: How to force a timeout on a system call? by maverick
in thread How to force a timeout on a system call? by Xxaxx

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.