ohho ohho - 2 years ago 95
Linux Question

How to prevent PHP script running more than once?

Currently, I tried to prevent an

script from running more than once:

$fp = fopen("/tmp/"."onlyme.lock", "a+");
if (flock($fp, LOCK_EX | LOCK_NB)) {
echo "task started\n";
while (true) {
// do something lengthy
flock($fp, LOCK_UN);
} else {
echo "task already running\n";

and there is a cron job to execute the above script every minute:

* * * * * php /usr/local/src/onlytask.php

It works for a while. After a few day, when I do:

ps auxwww | grep onlytask

I found that there are two instances running! Not three or more, not one. I killed one of the instances. After a few days, there are two instances again.

What's wrong in the code? Are there other alternatives to limit only one instance of the onlytask.php is running?

p.s. my
folder is not cleaned up.
ls -al /tmp/*.lock
show the lock file was created in day one:

-rw-r--r-- 1 root root 0 Dec 4 04:03 onlyme.lock

Answer Source

Now I check whether the process is running by ps and warp the php script by a bash script:


 PIDS=`ps aux | grep onlytask.php | grep -v grep`
 if [ -z "$PIDS" ]; then
     echo "Starting onlytask.php ..."
     php /usr/local/src/onlytask.php >> /var/log/onlytask.log &
     echo "onlytask.php already running."

and run the bash script by cron every minute.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download