Following this answer to limit only one instance of a php script running:
<?php
$fp = fopen("/tmp/one.txt", "r+");
if (flock($fp, LOCK_EX)) {
//
do_something_lengthy();
//
flock($fp, LOCK_UN);
} else {
echo "Couldn't get the lock!";
}
fclose($fp);
?>
My question is, will the flock‘ed one.txt file be unlock if the process die in the middle of do_something_lengthy(), i.e. before calling flock($fp, LOCK_UN)?
According to the manual page of
flock()that PHP uses internally, a lock is released when eitherflock()is called withLOCK_UNor when the descriptor is closed usingfclose().Upon script termination, either PHP or the OS will close the open file descriptors, thereby releasing the locks you may have.
Because of said behaviour this commit (5.3) and this one (5.2) were made to no longer do the unlocking in PHP itself.