A simple question. Do scripts that try to read a file locked with file_put_contents
that uses LOCK_EX
wait until the file is unlocked or fail reading and continue?

- 8,037
- 14
- 65
- 112
-
@chiliNUT I would need a huge file to try it, or wouldn't I? – Desmond Hume Nov 30 '13 at 19:49
-
2possible duplicate of [How can I use file\_put\_contents() with FILE\_APPEND | LOCK\_EX safety?](http://stackoverflow.com/questions/9009058/how-can-i-use-file-put-contents-with-file-append-lock-ex-safety) – mario Nov 30 '13 at 19:49
-
1`dd if=/dev/zero of=output.dat bs=1M count=10` creates a 1M x 10 = 10MB file, make a file as big as you need and use that – chiliNUT Nov 30 '13 at 19:51
-
@mario The author of the accepted answer says `So since file_get_contents() utilizes it [flock()], I'd assume it's the same`. It's an assumption, and even if it does use `flock()`, he doesn't really know for sure whether it uses `LOCK_NB` or not (left alone he's talking about `file_get_contents` for whatever reason while my question concerns locking files with `file_put_contents` and reading of such files in general). – Desmond Hume Nov 30 '13 at 20:02
-
1There's a more detailed answer in [should LOCK\_EX on both read & write be atomic?](http://stackoverflow.com/q/4899737). It's still not an authoritative answer (but I'd rather see new answers added there instead of a new duplicate). Btw, it's at least supposed *to wait*, regardless of the underlying implementation. – mario Nov 30 '13 at 20:07
2 Answers
The simple answer is that they don't block but fail. The answer by Groovepig is correct but verbose to the point of ambiguity and mario's comment is the most helpful "answer" out of this thread.
If J lock_ex-opens FILE.TXT, then K will receive an error message form file_put_contents until J unlocks the file, for example, by the completion of the locking file_put_contents call carried out by J.
After this K will be able to file_put_contents the file.
As a response to those questioning the validity of locking an append operation, while appends may be quick, if K writes to FILE.TXT while J's unlocked write operation has started, the behaviour is undefined but possiblities are that J's append will not be appended, could be appended in the wrong order or the ftell of K could cause Ks write to be bang smack in the middle of what J just wrote.
Appends are quick and its much less likely clash will happen but they can still happen and it can mean the difference between a file whose data is meaningful and a file whose data is gobbledygook.

- 467
- 2
- 14