【发布时间】:2019-04-07 07:41:36
【问题描述】:
以下代码在调用 file_get_contents 时会触发错误,尽管很少见,但该文件不存在,即使 file_exists 仅在上面的几个语句中被调用。
我相信在调用 file_exists 期间,该文件已被 cron 作业删除,错误已被触发。
$isRead = self::FILE_READ === $action;
$exists = file_exists($file);
$handle = fopen($file, ($isRead ? 'r' : 'c+'));
if ($handle) {
$locked = flock($handle, ($isRead ? LOCK_SH : LOCK_EX));
if ($locked) {
if ($exists) {
// Sometimes (very rarely) the following line triggers an error that
// $file does not exist
$data = (int)file_get_contents($file);
} else {
$data = 0;
}
if ($isRead) {
// Get Counter
flock($handle, LOCK_UN);
return $data;
}
// Update Counter
if (self::FILE_UPDATE === $action) {
$value += $data;
}
ftruncate($handle, 0);
rewind($handle);
fwrite($handle, $value);
flock($handle, LOCK_UN);
return true;
}
trigger_error("[FileCache] Failed to acquire lock for updating ${file}", E_USER_ERROR);
} else {
trigger_error("[FileCache] Failed to open file ${file}", E_USER_ERROR);
}
PHP 中的flock 是否保证文件不会被任何其他进程修改?还是仅限于当前流程?
另外,unlink 在 php 中是否尊重 flock?
【问题讨论】: