Home > Article > Backend Development > How to create a singleton background process in PHP
This article mainly introduces the method of creating a single background process in PHP, involving PHP's related operating techniques for starting, creating, judging, stopping and other processes. Friends in need can refer to it
The details are as follows:
You can start a PHP background process through the following statement:
$command = " php script.php "; $pid = exec("nohup $command > /dev/null 2>&1 & echo $!");
nohup means that this process is independent of the created user and can run in daemon mode .
If you need this background process to run as a singleton, you can use the following method to record/judge whether the process is running
//query the database for process id $query = "SELECT pid FROM `daemons` WHERE `pid` = '2013' LIMIT 1"; $result = mysql_query($query); $pid = mysql_result($result, 0, 'pid'); //check if the process is running exec("ps $pid", $pState); if((count($pState) >= 2) && !empty($pid)) { echo "RUNNING"; } else { echo "INACTIVE"; }
You can also write the pid to a file, but if you are in a distributed task environment, it is better to put it in the database
Stop a background process:
//check if the process from the database is running exec("ps $pid", $pState); if((count($pState) >= 2)) { //if the process is running, kill it exec("kill $pid"); //update database row with an empty process id }
PHPSingle caseDetailed explanation of how to use the pattern
PHP Implemented Redis multi-database selection functionSingle case class (detailed explanation)
php implements mongoDBSingle caseMode operation class steps detailed explanation
The above is the detailed content of How to create a singleton background process in PHP. For more information, please follow other related articles on the PHP Chinese website!