我需要确保一次只运行一份 Perl 脚本副本。根据建议here http://www.perlmonks.org/?node_id=590619我写了一个子程序来进行检查:
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;
}
}
但这不起作用。可能是什么问题?
您正在使用子范围内的词法文件句柄。什么时候check_instances
返回时,文件句柄自动关闭,从而释放锁。因此,除非两个副本完全相同地同时检查,否则您永远不会看到冲突。
确保只要脚本正在运行(或者只要您想要保持锁定),文件句柄就保持打开状态。例如:
{
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多变的 http://perldoc.perl.org/functions/state.html,如果您需要 Perl 5.10。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)