sub lock_file {
my ($lock_file, $block) = @_;
return unless defined $lock_file;
my $LOCKFH;
if (file_exist($lock_file)) {
sysopen($LOCKFH, "$lock_file", O_RDWR) || return undef;
} else {
sysopen($LOCKFH, "$lock_file", O_RDWR|O_CREAT|O_EXCL) || return undef;
}
my $lock_ret = 0;
my $pack;
if ($block) {
my $flags;
fcntl($LOCKFH, F_GETFL, $flags);
$flags &= !O_NONBLOCK;
my $fail_block = fcntl($LOCKFH, F_SETFL, $flags);
print "failed to set the lock to block mode.$!\n" if !$fail_block;
}
$pack = pack('ssqql', F_WRLCK, SEEK_SET, 0, 0, 0);
$lock_ret = fcntl($LOCKFH, F_SETLK, $pack);
if (!$lock_ret) {
close $LOCKFH;
return undef;
}
return $LOCKFH;
}
答案 0 :(得分:2)
尝试将flock与LOCK_NB一起使用,例如
use Fcntl qw(:DEFAULT :flock);
flock( $fh, LOCK_EX|LOCK_NB ) or die "failed to get lock";
... do code while having the lock ...
flock( $fh, LOCK_UN);
除此之外,我记得从旧时代开始,用NFS锁定总是有点特别,并不总能达到你的预期。这就是为什么在通过NFS共享邮箱时使用辅助文件的特殊锁定方案。我不确定这是否仍然适用于当前的NFS实现。