Search code examples
phpfile-exists

Checking if a php process is already running


I'm trying to check if a process is already running by using a temporal file demo.lock:

demo.php:

<?php
    $active=file_exists('demo.lock');
    if ($active)
    {
        echo 'process already running';
    }
    else
    {
        file_put_contents ('demo.lock', 'demo');
        sleep(10);  //do some job
        unlink ('demo.lock');
        echo 'job done';
    }
?>

however it doesn't seem to work: if I open demo.php twice it always shows "job done", maybe because it considers it the same process? is there some way to do it? I also tried with getmypid() with similar results.

Thanks


Solution

  • Well, sending some headers and flushing seems to work for me (not sure why), so now when I load the page shows "Start" and if I hit the refresh button on the browser before completing the process, the warning message:

    <?php
    
    $file = @fopen("demo.lock", "x");
    if($file === false)
    {
        echo "Unable to acquire lock; either this process is already running, or permissions are insufficient to create the required file\n";
        exit;
    }
    
    header("HTTP/1.0 200 OK");
    ob_start();
    echo "Starting";
    header('Content-Length: '.ob_get_length(),true);
    ob_end_flush();
    flush();
    
    fclose($file); // the fopen call created the file already
    sleep(10); // do some job
    unlink("demo.lock");    
    ?>
    

    Thanks for all the answers and suggestions so far