I trying to implmente a simpler version of the code in this answer: How to detect whether a PHP script is already running?
The problem described here is my EXACT situation. I want to prevent cron from launching the same script if it's already running.
I started with this simple test code:
<?php 
   $script_name = __FILE__;
   $lock_file_name = basename($script_name, ".php") . ".lock";
   $fp = fopen($lock_file_name, "c");
   if (flock($fp, LOCK_EX)) {  // acquire an exclusive lock
       //ftruncate($fp, 0);      // truncate file
       //fwrite($fp, "Write something here\n");
       //fflush($fp);            // flush output before releasing the lock
       flock($fp, LOCK_UN);    // release the lock
       echo "GOT LOCK\n";
       sleep(20);
   } else {
       echo "Couldn't get the lock!\n";
   }
   flock($fp, LOCK_UN);    // release the lock
   fclose($fp);
   
?>
As I understand it, I launch this code in one console and read the Got Lock. If I launch it in another console the I should get the Coudn't get the lock message. Howver I get the Got Lock message both times.
What am I doing wrong?