note 62188 deleted from function.flock by danbrown
| From: | danbrown@php.net | Date: | Mon, 18 May 2009 00:38:52 +0000 |
| Subject: | note 62188 deleted from function.flock by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-155404@lists.php.net to get a copy of this message | ||
Note Submitter: dranger at export dash japan dot com
----
jbr at ya-right dot com has the wrong idea of what flock is supposed to do.
flock is *supposed* to "hang" until the other lock is released. This is the intended
behavior on ALL systems, not just Windows.
If this behavior is not acceptable, flock already has a mechanism to deal with this: LOCK_NB. Just
add LOCK_NB to the second argument, and flock will not "hang." For example:
<?php
flock($fp, LOCK_EX+LOCK_NB, $wouldblock)
?>
and flock will return TRUE or FALSE immediately, setting $wouldblock to 1 if the call would have
blocked.
You DO NOT need to muck about with while loops, usleep, "clever" md5 + time hashing
tricks, random numbers, or any of this nonsense. These techniques defeat the entire point of using
flock in the first place.
What's worse about jbr's code is that it introduces a bug that flock was meant to fix in
the first place! It's called a "race condition" - here's an example:
1. Program A checks that file "fakelock" exists. It doesn't.
2. Processor switches to Program B.
3. Program B checks that file "fakelock" exists. It doesn't.
4. Program A writes its unique key, "A" to the file, and checks that its key is correct.
It is.
5. Program B writes its unique key "B" to the file, and because its file pointer was
pointing at the beginning of the file, it overwrites "A" with "B". It checks
that its key is correct. It is.
6. Now Program A and Program B can both write to file "$fl_file.", and both overwrite the
file that was to be protected. There are many other situations in which this code will fail as well.
To the best of my knowledge, YOU CANNOT MAKE YOUR OWN FLOCK USING JUST PHP NO MATTER HOW HARD YOU
TRY. YOU MUST USE FLOCK.
If you have Windows ISAPI, you may have trouble with flock working correctly because it is
multithreaded, but this kind of fix will not correct the situation.