bdizzle
bdizzle

Reputation: 419

regulate execution time of function in perl

I have a command line function I'd like to execute in Perl. However, I only want it to run for up to X seconds. If at X seconds, no result is returned, I want to move on. For instance, if I wanted to do something like

sub timedFunction {
 my $result = `df -h`;
 return $result;
}

How could I kill the wait for the command line command to finish if it's not returned any values after 3 seconds?

Upvotes: 1

Views: 288

Answers (1)

chrsblck
chrsblck

Reputation: 4088

You want to use an alarm.

local $SIG{ALRM} = sub { die "Alarm caught. Do stuff\n" };

#set timeout
my $timeout = 5;
alarm($timeout);

# some command that might take time to finish, 
system("sleep", "6");
# You may or may not want to turn the alarm off
# I'm canceling the alarm here
alarm(0);   
print "See ya\n";

You obviously don't have to "die" here when the alarm signal is caught. Say get the pid of the command you called and kill it.

Here's the output from the above example:

$ perl test.pl 
Alarm caught. Do stuff
$ 

Notice the print statement didn't execute after the system call.

It's worth noting that it isn't recommended to use alarm to time out a system call unless it's an 'eval/die' pair according to the perldoc.

Upvotes: 1

Related Questions