Php flock and fread and fwrite

I see people using a herd like this:

if (!$fp = fopen($file_name, 'wb')) { return FALSE; } if (flock($fp, LOCK_EX)) { fwrite($fp, serialize($data)); flock($fp, LOCK_UN); } 

Also this:

 if (!$fp = @fopen($file_name, 'rb')) { return FALSE; } flock($fp, LOCK_SH); $data = ''; if (filesize($file_name) > 0) { $data = unserialize(fread($fp, filesize($file_name))); } 

But isn't it possible for someone else to edit the file between the fopen call and the flock call? same question for fread


EDIT:
To clarify why I ask about this ... I base my question on the code here ,. mysql-caching situation, what to stop 20 people from all having access to the file at the same time, if all of them can get between fopen and flock?

Is this code reliable?

+7
source share
2 answers

You are asking:

is there any chance that someone else will edit the file between calling fopen and calling flock? same question for fread

Yes, no, maybe. Short answer: assume yes and proceed with caution.

Yes, the fact is that traditional flock () -blocking is just advisory, so other processes (or even the same process) can freely ignore locks. In practice, this is not a problem, since flock () is used by good client code - you do not read until you get LOCK_SH, and you do not write if you did not receive LOCK_EX - specific files.

No, in this PHP implementation of flock () may be required on certain operating systems, in the documentation , which may also require support from the file system (for example, as in the mand option on Linux). Thus, other processes could not ignore these locks.

It is possible that the thread subsystem in PHP 5 implements some accounting blocking beyond the limits provided by the operating system. This can, for example, prevent the same process (but not another), if its own other advisory locks are not taken into account. Behavior may surprise some. However, such a lock will not be mandatory between unrelated processes.

For portability, just assume the weakest semantics (β€œyes” above) and limit flock () to the correct code on specially created lock files of the application selected in advance.

+6
source

The first passage is insane, if you cannot lock the file, you are not writing. If someone edited the file between fopen() and flock() , your file descriptor will point to the most recent incarnation, since fopen() associated with the stream, not the snapshot.

The second example is not guaranteed to work because the return value of flock() not checked, so if you have not acquired a lock yet, the subsequent code will be executed anyway.

[edit] The remote statement that a read lock does not matter, actually does it, as explained in the comments below :)

+2
source

All Articles