PHP Advanced Programming Example: Writing Daemons

  • 2021-07-16 02:00:33
  • OfStack

1. What is a daemon

A daemon is a process that is detached from the terminal and runs in the background. The daemon is separated from the terminal in order to prevent the information of the process during execution from being displayed on any terminal and the process will not be interrupted by the terminal information generated by any terminal.

For example, apache, nginx, mysql are all daemons

2. Why develop daemons

Many programs exist in the form of services, and they have no terminal or UI interaction. They may interact with other programs in other ways, such as TCP/UDP Socket, UNIX Socket and fifo. Program 1 enters the background once it is started, and he starts to deal with tasks until the conditions are met.

3. When to use daemons to develop applications

Taking my current needs as an example, I need to run a program, then listen to a certain port, continuously accept the data initiated by the server, then analyze and process the data, and then write the results to the database; I use ZeroMQ to send and receive data.

If I don't use daemon to develop this program, the program 1 will occupy the current terminal window frame once it runs, and it will be affected by the current terminal keyboard input, so it is possible that the program will exit by mistake.

4. Daemon security issues

We want the program to run in a non-superuser, so that 1 because the program is controlled by hackers due to vulnerabilities, attackers can only inherit the running rights, but cannot obtain superuser rights.

We hope that the program can only run one instance, and if we don't run colleagues, we will open more than two programs, because there will be port conflicts and other problems.

5. How to develop daemons

Example 1. Daemon instantiation


<?php
class ExampleWorker extends Worker {

 #public function __construct(Logging $logger) {
 # $this->logger = $logger;
 #}

 #protected $logger;
 protected static $dbh;
 public function __construct() {

 }
 public function run(){
  $dbhost = '192.168.2.1';  //  Database server 
  $dbport = 3306;
   $dbuser = 'www';  //  Database user name 
 $dbpass = 'qwer123';    //  Database password 
  $dbname = 'example';  //  Database name 

  self::$dbh = new PDO("mysql:host=$dbhost;port=$dbport;dbname=$dbname", $dbuser, $dbpass, array(
   /* PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'', */
   PDO::MYSQL_ATTR_COMPRESS => true,
   PDO::ATTR_PERSISTENT => true
   )
  );

 }
 protected function getInstance(){
 return self::$dbh;
  }

}

/* the collectable class implements machinery for Pool::collect */
class Fee extends Stackable {
 public function __construct($msg) {
  $trades = explode(",", $msg);
  $this->data = $trades;
  print_r($trades);
 }

 public function run() {
  #$this->worker->logger->log("%s executing in Thread #%lu", __CLASS__, $this->worker->getThreadId() );

  try {
   $dbh = $this->worker->getInstance();
   
   $insert = "INSERT INTO fee(ticket, login, volume, `status`) VALUES(:ticket, :login, :volume,'N')";
   $sth = $dbh->prepare($insert);
   $sth->bindValue(':ticket', $this->data[0]);
   $sth->bindValue(':login', $this->data[1]);
   $sth->bindValue(':volume', $this->data[2]);
   $sth->execute();
   $sth = null;
   
   /* ...... */
   
   $update = "UPDATE fee SET `status` = 'Y' WHERE ticket = :ticket and `status` = 'N'";
   $sth = $dbh->prepare($update);
   $sth->bindValue(':ticket', $this->data[0]);
   $sth->execute();
   //echo $sth->queryString;
   //$dbh = null;
  }
  catch(PDOException $e) {
   $error = sprintf("%s,%s\n", $mobile, $id );
   file_put_contents("mobile_error.log", $error, FILE_APPEND);
  }
 }
}

class Example {
 /* config */
 const LISTEN = "tcp://192.168.2.15:5555";
 const MAXCONN = 100;
 const pidfile = __CLASS__;
 const uid = 80;
 const gid = 80;
 
 protected $pool = NULL;
 protected $zmq = NULL;
 public function __construct() {
  $this->pidfile = '/var/run/'.self::pidfile.'.pid';
 }
 private function daemon(){
  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) {
    // we are the parent
    //pcntl_wait($status); //Protect against Zombie children
   exit($pid);
  } else {
   // we are the child
   file_put_contents($this->pidfile, getmypid());
   posix_setuid(self::uid);
   posix_setgid(self::gid);
   return(getmypid());
  }
 }
 private function start(){
  $pid = $this->daemon();
  $this->pool = new Pool(self::MAXCONN, \ExampleWorker::class, []);
  $this->zmq = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REP);
  $this->zmq->bind(self::LISTEN);
  
  /* Loop receiving and echoing back */
  while ($message = $this->zmq->recv()) {
   //print_r($message);
   //if($trades){
     $this->pool->submit(new Fee($message));
     $this->zmq->send('TRUE'); 
   //}else{
   // $this->zmq->send('FALSE'); 
   //}
  }
  $pool->shutdown(); 
 }
 private function stop(){

  if (file_exists($this->pidfile)) {
   $pid = file_get_contents($this->pidfile);
   posix_kill($pid, 9); 
   unlink($this->pidfile);
  }
 }
 private function help($proc){
  printf("%s start | stop | help \n", $proc);
 }
 public function main($argv){
  if(count($argv) < 2){
   printf("please input help parameter\n");
   exit();
  }
  if($argv[1] === 'stop'){
   $this->stop();
  }else if($argv[1] === 'start'){
   $this->start();
  }else{
   $this->help($argv[0]);
  }
 }
}

$cgse = new Example();
$cgse->main($argv);

5.1. Program initiation

The following is the code that enters the background after the program starts

The process ID file is used to judge the current process state. If the process ID file exists, the program is running through the code file_exists ($this- > pidfile), but then the process by kill needs to manually delete the file to run


private function daemon(){
  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) {
   // we are the parent
   //pcntl_wait($status); //Protect against Zombie children
   exit($pid);
  } else {
   // we are the child
   file_put_contents($this->pidfile, getmypid());
   posix_setuid(self::uid);
   posix_setgid(self::gid);
   return(getmypid());
  }
 }

After the program starts, the parent process will be pushed out, the child process will run in the background, the child process authority will be switched from root to the specified user, and pid will be written into the process ID file at the same time.

5.2. Program Stop

The program stops, just read the pid file, and then call posix_kill ($pid, 9); Finally, the file is deleted.


private function stop(){

  if (file_exists($this->pidfile)) {
   $pid = file_get_contents($this->pidfile);
   posix_kill($pid, 9); 
   unlink($this->pidfile);
  }
 }


Related articles: