I made this little script to test it out
header('Content-type:text/plain; charset=utf-8');
$dir = dirname(__FILE__);
$file = $dir.'/testflock.lock';
$fh = fopen($file, 'w+');
$unlocked = flock($fh, LOCK_EX | LOCK_NB);
echo 'Locked: '.$file.' ';var_dump(!$unlocked);echo PHP_EOL;
if($unlocked){
sleep(10);
throw new Exception();
}
and for me it it took the OS to unlock the file about 2-5 seconds after the script finished executing if it does not throw any Exception, and up to 2-5 seconds after the script stopped because of the thrown Exception.
Keep in mind that as of php 5.3.2 fclose($fh)
will not unlock the file, and the file will remain locked unless you unlock it with php or you will have to wait for the OS to unlock it, which might never happen if there is some bug (this happened to me)
To unlock the file:
flock($fh,LOCK_UN);
To close the file handle (will be called automatically when the script finishes executing)
fclose($fh);
Locking the file without the LOCK_NB
will cause the script to wait for the file to get unlocked.