I have a php-cli
script that is run by cron
every 5 minutes
. Because this interval is short, multiple processes
are run at the same time. That's not what I want, since this script has to write inside a text file a numeric id
that is incremented each time. It happens that writers
are writing at the same time on this text file, and the value written is incorrect.
I have tried to use php's flock
function to block writing in the file, when another process is writing on it but it doesnt work.
$fw = fopen($path, 'r+');
if (flock($fw, LOCK_EX)) {
ftruncate($fw, 0);
fwrite($fw, $latestid);
fflush($fw);
flock($fw, LOCK_UN);
}
fclose($fw);
So I suppose that the solution to this is create a bash
script that verifies if there is an instance of this php script
that is running, if so it should wait until it finished. But I dont know how to do it, any ideas?