By referring to flock(): removing locked file without race condition? and Will flock'ed file be unlocked when the process die unexpectedly? ,
I produce the following code. My intention is to allow only single thread / single process to run the critical section code, within any given time.
<?php
// Exclusive locking based on function parameters.
$lockFileName = '/tmp/cheok.lock';
// Create if doesn't exist.
$lockFile = fopen($lockFileName, "w+");
if (!flock($lockFile, LOCK_EX)) {
throw new \RumtimeException("Fail to perform flock on $lockFileName");
}
echo "start critical section...\n";
sleep(10);
echo "end critical section.\n";
// Warning: unlink(/tmp/cheok.lock): No such file or directory in
unlink($lockFileName);
flock($lockFile, LOCK_UN);
I will always get the warning
Warning: unlink(/tmp/cheok.lock): No such file or directory in
when the 2nd waiting process continues his execution, the 1st process already remove the physical disk file. The 2nd process tries to unlink
file, which is already deleted by the 1st process.
And, what if, there is 3rd process join in, and tries the perform fopen
while 2nd process is trying to perform unlink
?
In short, what is the correct way to perform lock file cleanup?