How to detect whether a PHP script is already running?

后端 未结 9 1417
借酒劲吻你
借酒劲吻你 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:53

    A common way for *nix daemons (though not necessarily PHP scripts, but it will work) is to use a .pid file.

    When the script starts check for the existence of a .pid file named for the script (generally stored in /var/run/). If it doesn't exist, create it setting its contents to the PID of the process running the script (using getmypid) then continue with normal execution. If it does exist read the PID from it and see if that process is still running, probably by running ps $pid. If it is running, exit. Otherwise, overwrite its contents with your PID (as above) and continue normal execution.

    When execution finished, delete the file.

提交回复
热议问题