Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP flock() behaviour difference on Windows vs Linux

Tags:

linux

php

windows

I am executing the same code snippet on a Windows machine and a Linux machine. Both are running PHP 5.4:

$file = "lock.txt";
$fp = fopen($file, "w+");
flock($fp, LOCK_EX);
var_dump(@file_put_contents($file, 'hello' . rand()));
flock($fp, LOCK_UN);
fclose($fp);

On the Windows machine, the file_put_contents() operation fails and returns false. On the Linux machine, it succeeds.

I'm trying to figure out which of these two behaviours is actually correct and how I can standardize the behaviour across both systems (for the record, my goal is to have the file_put_contents() fail. I don't need it to be robust or atomic, I just want it to fail.)

I have seen plenty of other questions about this topic, but they all seem to relate to multiple scripts accessing the same file, which isn't the situation here.

like image 474
Swiftheart Avatar asked Aug 15 '26 15:08

Swiftheart


1 Answers

It appears the documentation for flock() does answer this question, albeit not as fully as it could. The documentation does state

flock() uses mandatory locking instead of advisory locking on Windows

which is clear enough but I was thrown off by the first comment which reads

Flock utilizes ADVISORY locking only; that is, other processes may ignore the lock completely

I was interpreting that to mean that my own process would respect the lock implicitly; actually it seems to mean something like, "We assume that--once you're using flock() in the first place--you will remember to check the lock's status before any writes, but remember that other programs may not be doing so."

like image 99
Swiftheart Avatar answered Aug 18 '26 04:08

Swiftheart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!