【问题标题】:regulate execution time of function in perl在perl中调节函数的执行时间
【发布时间】:2013-03-28 04:43:11
【问题描述】:

我有一个想在 Perl 中执行的命令行函数。但是,我只希望它最多运行 X 秒。如果在 X 秒内没有返回结果,我想继续。例如,如果我想做类似

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

如果命令行命令在 3 秒后没有返回任何值,我怎么能终止等待呢?

【问题讨论】:

标签: perl


【解决方案1】:

你想使用闹钟。

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";

当警报信号被捕获时,您显然不必在这里“死”。说获取你调用的命令的 pid 并杀死它。

这是上例的输出:

$ perl test.pl 
Alarm caught. Do stuff
$ 

注意系统调用后打印语句没有执行。

值得注意的是,除非根据perldoc,它是“eval/die”对,否则不建议使用警报来超时系统调用。

【讨论】:

  • 注:每个进程一次只能运行一个本机alarm,因此递归之类的东西不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多