My first experience with flock() was quite problematic and besides I wanted a solution that would work cross-platform (at least to some reasonable degree on Windows). And it's not really complicated as compared to using flock(). Anyway, I've done some more testing and flock() seems to work well. And the documentation must be wrong or outdated, because LOCK_NB works on Windows, too - at least on XP with PHP 5.2.4. I have tested this code:
PHP Code:
$lockFile = "test.lock";
$fp = fopen($lockFile, 'w+');
echo "fopen<br/>"; ob_flush(); flush();
if(!flock($fp, LOCK_EX | LOCK_NB)) {
echo 'Unable to obtain lock, script stopped.';
exit;
}
echo "running script after flock...<br/>"; ob_flush(); flush();
sleep(10);
fclose($fp);
echo "end.";
Now my question is - in this example is there a possibility of deadlock? Theoretically, the lock should be released when the script ends but what if the script ends unexpectedly due to some server error? Is it possible the lock will never be released then? If so then what can be done about it to handle it automatically?
Bookmarks