flock 是否跨进程锁定文件?

Does flock lock the file across processes?

以下代码在调用 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);
}

flock in PHP是否保证文件不会被任何其他进程修改?还是仅限于当前进程?

此外,unlink php 是否尊重 flock

在Linux(和其他 UNIX)系统上,flock() 纯粹是建议锁。它会阻止其他进程在与 flock() 相同的文件上获得冲突锁,但不会阻止文件被修改或删除。

在 Windows 系统上,flock() 是强制锁定,将防止对文件进行修改。