note 108270 added to splfileobject.flock
| From: | mr.stobbe | Date: | Thu, 12 Apr 2012 23:05:19 +0000 |
| Subject: | note 108270 added to splfileobject.flock | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-187095@lists.php.net to get a copy of this message | ||
It's important to note that digitalprecision's assertion that the ftruncate() call is
redundant is not true. It is necessary.
The fopen call (in this case the SplFileObject constructor) will truncate the file, but there's
a race condition similar to the following (ignoring buffering and such for a moment):
Process A: fopen("somefile.txt", "w")
Process A: fwrite("line 1\n")
Process B: fopen("somefile.txt", "w")
Process A: fwrite("line 2\n")
Process A: fclose()
Process B: flock(LOCK_EX)
Process B: fwrite("exclusive line 1\n");
Process B: flock(LOCK_UN)
Process B: fclose()
Expected File Contents:
exclusive line 1
Actual File Contents:
line 2
exclusive line 1
If the file is written to by another process between the open call and the lock call, there will be
unexpected data at the beginning of the file. This is why the truncate call is needed after an
exclusive lock is obtained.
----
Server IP: 64.71.164.2
Probable Submitter: 166.108.254.215
----
Manual Page -- http://www.php.net/manual/en/splfileobject.flock.php
Edit -- https://master.php.net/note/edit/108270
Del: integrated -- https://master.php.net/note/delete/108270/integrated
Del: useless -- https://master.php.net/note/delete/108270/useless
Del: bad code -- https://master.php.net/note/delete/108270/bad+code
Del: spam -- https://master.php.net/note/delete/108270/spam
Del: non-english -- https://master.php.net/note/delete/108270/non-english
Del: in docs -- https://master.php.net/note/delete/108270/in+docs
Del: other reasons-- https://master.php.net/note/delete/108270
Reject -- https://master.php.net/note/reject/108270
Search -- https://master.php.net/manage/user-notes.php