This article mainly introduces the method of PHP to create a single background process, involving PHP for process start, create, judge, stop and other related operations skills, the need for friends can refer to the next
Specific as follows:
You can start a PHP background process by using the following statement:
$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 be run as a daemon.
If you want this background process to run as a singleton, you can record/determine if the process is running by using the following method
Query the database for process id$query = "Select pid from ' daemons ' WHERE ' pid ' = ' LIMIT 1 '; $result = mysql_query ($query); $pid = mysql_result ($result, 0, ' pid '),//check if the process is runningexec ("PS $pid", $pState); if ((Count ($pSta TE) >= 2) &&!empty ($pid)) {echo "RUNNING";} Else{echo "INACTIVE";}
You can also write the PID to a file, but in a distributed task environment, it is better to put it in the database.
To 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 and an empty process ID}
Related recommendations:
PHP Single-case mode using a detailed approach
The Redis multi-Library selection feature in PHP implementation Singleton class (detailed)
PHP implementation MongoDB Singleton mode operation steps