如何确保一次只运行一个Perl脚本副本? [英] How can I ensure only one copy of a Perl script is running at a time?
问题描述
我需要确保一次只运行我的Perl脚本的一个副本.根据此处的建议,我写了一个子代码进行检查:
I need to ensure that only one copy of my Perl script is running at a time. According to the suggestions here I wrote a sub to do the check:
sub check_instances {
open my $fh, '<', $0 or die $!;
unless (flock($fh, LOCK_EX|LOCK_NB)) {
print "$0 is already running. Exiting.\n";
exit 1;
}
}
但是它不起作用.可能是什么问题?
But it doesn't work. What can be the issue?
推荐答案
您正在使用范围在子对象内的词法文件句柄.当返回check_instances
时,文件句柄将自动关闭,从而释放锁定.因此,除非有两个副本完全同时检查,否则您永远不会看到冲突.
You're using a lexical filehandle scoped inside the sub. When check_instances
returns, the filehandle is automatically closed, which releases the lock. So you'll never see a conflict unless two copies check at exactly the same time.
确保只要脚本正在运行(或者只要您想保持锁定),文件句柄就保持打开状态.例如:
Ensure that the filehandle remains open as long as the script is running (or as long as you want to maintain the lock). For example:
{
my $fh;
sub check_instances {
return if $fh; # We already checked
open $fh, '<', $0 or die $!;
unless (flock($fh, LOCK_EX|LOCK_NB)) {
print "$0 is already running. Exiting.\n";
exit 1;
}
}
} # end scope of $fh
如果使用 state
变量,这也是一个好地方.您可以要求使用Perl 5.10.
This would also be a good place to use a state
variable, if you can require Perl 5.10.
这篇关于如何确保一次只运行一个Perl脚本副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!