php implements simple daemon creation opening and closing operations
- 2021-12-13 16:36:40
- OfStack
This article illustrates how php implements simple daemon creation, opening, and closing operations. Share it for your reference, as follows:
The premise is to install pcntl extension, which can be passed through
php -m
Check to see if it is installed
<?php
class Daemon {
private $pidfile;
function __construct() {
$this->pidfile = dirname(__FILE__).'/daemontest.pid';
}
private function startDeamon() {
if (file_exists($this->pidfile)) {
echo "The file $this->pidfile exists.\n";
exit();
}
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
echo 'start ok';
exit($pid);
} else {
// we are the child
file_put_contents($this->pidfile, getmypid());
return getmypid();
}
}
private function start(){
$pid = $this->startDeamon();
while (true) {
file_put_contents(dirname(__FILE__).'/test.txt', date('Y-m-d H:i:s'), FILE_APPEND);
sleep(2);
}
}
private function stop(){
if (file_exists($this->pidfile)) {
$pid = file_get_contents($this->pidfile);
posix_kill($pid, 9);
unlink($this->pidfile);
}
}
public function run($argv) {
if($argv[1] == 'start') {
$this->start();
}else if($argv[1] == 'stop') {
$this->stop();
}else{
echo 'param error';
}
}
}
$deamon = new Daemon();
$deamon->run($argv);
Start
php deamon.php start
Shut down
php deamon.php stop
For more readers interested in PHP related contents, please check the topics on this site: "Summary of PHP Process and Thread Operation Skills", "Summary of PHP Network Programming Skills", "Introduction to PHP Basic Syntax", "Encyclopedia of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"
I hope this article is helpful to everyone's PHP programming.