问题
running this code twice :
$fp = @fopen('test.test', "wb");
if (flock($fp, LOCK_NB | LOCK_EX)){
@fwrite($fp, $data);
echo 'written';
sleep(5);
}else{
echo 'skipped , ok';
}
@flock($fp, LOCK_UN);
@fclose($fp);
always gives me the output of "written"
Means the LOCK_NB
is skipped , any clues (on both winbdows and unix)
EDIT (2012-03-29 still not fixed): https://bugs.php.net/bug.php?id=54453&edit=3 PHP Bug #54453
回答1:
When using Apache+PHP I was tricked into believing LOCK_NB was ignored (it wasn't, it was the browser waiting for the first request to finish).
Because I was making 2 requests with the same browser, the browser was waiting for the first call to finish before making the next one (even ignoring a "Connection: close" header).
Using 2 separate browsers (in my case Chrome + Firefox, or Chrome + wget on the server) I concluded LOCK_NB worked just fine.
If a file in w+ mode was locked with LOCK_EX | LOCK_NB, attempting another LOCK_EX | LOCK_NB on the same file returned false (the intended behaviour).
回答2:
LOCK_NB works only when :
- File is locked with
LOCK_SH
and you do aLOCK_EX|LOCK_NB
- File is locked with
LOCK_EX
and you do aLOCK_SH|LOCK_NB
LOCK_NB is ignored if :
- File is locked with
LOCK_EX
and you do aLOCK_EX|LOCK_NB
- File is locked with
LOCK_SH
and you do aLOCK_SH|LOCK_NB
i guess this is a bug ? or they need to make a LOCK_NB2 ? i reported this as a bug to PHP.NET .
EDIT (2012-03-22 still not fixed): https://bugs.php.net/bug.php?id=54453&edit=3 PHP Bug #54453
来源:https://stackoverflow.com/questions/5524073/lock-nb-ignored