Introduction to how to create a singleton background process in PHP

巴扎黑
Release: 2023-03-15 06:08:02
Original
1044 people have browsed it

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 $!");
Copy after login

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";
}
Copy after login

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
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!