Home  >  Article  >  Backend Development  >  Introduction to how to create a singleton background process in PHP

Introduction to how to create a singleton background process in PHP

巴扎黑
巴扎黑Original
2017-08-13 11:30:591015browse

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 the following

Examples of this article The method of creating a singleton background process in PHP. Share it with everyone for your reference, 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 one User, 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 use pid is written to a file, but if 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
}

The above is the detailed content of Introduction to how to create a singleton background process in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn