Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 631
Borgtex Avatar asked Apr 26 '10 16:04

Borgtex


Video Answer


2 Answers

Works for me.

Make sure the script can create a file in the directory. Uncomment the "unlink" line and run the script and check if the lock file exists in the directory. If you don't see it then it's a directory permissions issue.

like image 53
zaf Avatar answered Oct 07 '22 01:10

zaf


Can't be sure about what's wrong with your specific case assuming a "normal, easy" environment because it works for me, but at least you have a race condition in your code. What if you start two processes at the exact same time, and that both find that demo.lock does not exist?

You can use fopen with the x mode to prevent this from happening. The X mode tries to create the file; if it already exists, it fails and generates an E_WARNING error (hence the shut-up operator). Since filesystem operations are atomic on a drive, it is guaranteed that only one process at a time can hold the file.

<?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;
}

fclose($file); // the fopen call created the file already
sleep(10); // do some job
unlink("demo.lock");
echo "Job's done!\n";

?>

I've tested it here and it seems to work.

like image 30
zneak Avatar answered Oct 07 '22 01:10

zneak