在PHP中,如何测试文件是否已被flock
锁定?例如,如果另一个正在运行的脚本调用了以下内容:
$fp = fopen('thefile.txt', 'w');
flock($fp, LOCK_EX);
答案 0 :(得分:21)
if (!flock($fp, LOCK_EX|LOCK_NB, $wouldblock)) {
if ($wouldblock) {
// another process holds the lock
}
else {
// couldn't lock for another reason, e.g. no such file
}
}
else {
// lock obtained
}
如docs中所述,使用LOCK_NB
进行非阻塞尝试以获取锁定,并在失败时检查$wouldblock
参数以查看其他内容是否存在锁定
答案 1 :(得分:-2)
检查如下:
if (!flock($file, LOCK_EX)) {
throw new Exception(sprintf('File %s is locked', $file));
}
fwrite($file, $write_contents);