How to create a singleton background process in PHP

墨辰丷
Release: 2023-03-27 11:46:01
Original
1398 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 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 $!");
Copy after login

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

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

Related recommendations:

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!

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!