Example of how to create a single backend process in PHP and a background process
This example describes how to create a single-instance background process in PHP. We will share this with you for your reference. The details are as follows:
You can use the following statement to start a PHP background process:
$ Command = "php script. php"; $ pid = exec ("nohup $ command>/dev/null 2> & 1 & echo $! ");
Nohup indicates that the process is independent of the created user and can run in daemon mode.
If you need to run the background process as a Singleton, you can use the following method to record/determine whether the process is running
// Query the database for process id $ query = "SELECT pid FROM 'daemons' WHERE 'pid '= '000000' LIMIT 1"; $ result = mysql_query ($ query ); $ pid = mysql_result ($ result, 0, 'pid '); // check if the process is runningexec ("ps $ pid", $ pState ); if (count ($ pState)> = 2 )&&! Empty ($ pid) {echo "RUNNING";} else {echo "INACTIVE ";}
You can also write the pid to a file, but it is better to store it in a database if it is in a distributed task environment.
Stop a background process:
// Check if the process from the database is runningexec ("ps $ pid", $ pState); if (count ($ pState)> = 2 )) {// if the process is running, kill itexec ("kill $ pid"); // update database row with an empty process id}