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:~>