Joyce Babu
Joyce Babu

Reputation: 20654

Does flock lock the file across processes?

The following code triggers an error, though very rarely, when calling file_get_contents that the file does not exist, even though file_exists was called only a few statements above.

I believe that the file got deleted, by a cron job, between the time file_exists was called the error was triggered.

$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);
}

Does flock in PHP guarantee that the file will not be modified by any other processes? Or is it limited to the current process?

Also, does unlink in php honour flock?

Upvotes: 2

Views: 1040

Answers (1)

user149341
user149341

Reputation:

On Linux (and other UNIX) systems, flock() is purely a advisory lock. It will prevent other processes from obtaining a conflicting lock on the same file with flock(), but it will not prevent the file from being modified or removed.

On Windows systems, flock() is a mandatory lock, and will prevent modifications to the file.

Upvotes: 1

Related Questions