How to detect whether a PHP script is already running?

后端 未结 9 1337
借酒劲吻你
借酒劲吻你 2021-01-31 11:26

I have a cron script that executes a PHP script every 10 minutes. The script checks a queue and processes the data in the queue. Sometimes the queue has enough data to last ov

9条回答
  •  失恋的感觉
    2021-01-31 11:43

    I know this is an old question, but there's an approach which hasn't been mentioned before that I think is worth considering.

    One of the problems with a lockfile or database flag solution, as already mentioned, is that if the script fails for some reason other than normal completion it won't release the lock. And therefore the next instance won't start until the lock is either manually cleared or cleared by a clean-up function.

    If, though, you are certain that the script should only ever be running once, then it's relatively easy to check from within the script whether it is already running when you start it. Here's some code:

    function checkrun() {
        exec("ps auxww",$ps);
        $r = 0;
        foreach ($ps as $p) {
            if (strpos($p,basename(__FILE__))) {
                $r++;
                if ($r > 1) {
                    echo "too many instances, exiting\n";
                    exit();
                }
            }
        }
    }
    

    Simply call this function at the start of the script, before you do anything else (such as open a database handler or process an import file), and if the same script is already running then it will appear twice in the process list - once for the previous instance, and once for this one. So, if it appears more than once, just exit.

    A potential gotcha here: I'm assuming that you will never have two scripts with the same basename that may legitimately run simultaneously (eg, the same script running under two different users). If that is a possibility, then you'd need to extend the checking to something more sophisticated than a simple substring on the file's basename. But this works well enough if you have unique filenames for your scripts.

提交回复
热议问题