PHP Advanced Programming Example: Writing daemon _php tips

Source: Internet
Author: User

1. What is a daemon

A daemon is a process that is detached from the terminal and runs in the background. The daemon is detached from the terminal in order to avoid the information that the process is performing on any terminal and the process will not be interrupted by terminal information generated by any terminal.

For example, Apache, Nginx, MySQL are daemons.

2. Why the development daemon

Many programs exist in service form, he has no terminal or UI interaction, and it may interact with other programs in other ways, such as tcp/udp socket, UNIX socket, FIFO. Once the program is started, it enters the background, and when the condition is met, he starts working on the task.

3. When to use daemons to develop applications

Taking my current requirements as an example, I need to run a program, listen to a port, continue to receive data from the server, and then parse and process the data, then write the results to the database. I use ZEROMQ to implement data transceiver.

If I do not use daemons to develop the program, once the program is running will occupy the current terminal window frame, and is affected by the current terminal keyboard input, it is possible that the program mistakenly exit.

4. Security aspects of the daemon process

We want the program to run in a non-superuser, so that once the bug is controlled by the program, the attacker can only inherit the run and not get superuser privileges.

We want the program to run only one instance and not run a colleague to open more than two programs because there are port conflicts and so on.

5. How to develop the daemon process

Example 1. daemon Example

<?php class Exampleworker extends Worker {#public function __construct (Logging $logger) {# $this->logger = $lo
 Gger;
 #} #protected $logger;
 protected static $DBH;  Public Function __construct () {} public Function run () {$dbhost = ' 192.168.2.1 ';
   Database server $dbport = 3306;  $dbuser = ' www ';    Database username $dbpass = ' qwer123 ';  Database Password $dbname = ' example '; Database name self:: $DBH = new PDO ("mysql:host= $dbhost;p ort= $dbport;d bname= $dbname", $dbuser, $dbpass, Array (/* PDO::MYSQ L_attr_init_command => ' SET NAMES \ utf8\ ',/pdo::mysql_attr_compress => true, pdo::attr_persistent => t

 Rue));
  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); The 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::p idfile.
 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 ());
  The 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-&GT;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 launch

Here is the code that goes backstage after the program starts

The process ID file is used to determine the current process state, if the process ID file exists indicating that the program is running, implemented through code file_exists ($this->pidfile), but the process is killed by deleting the file manually to run

Private Function Daemon () {
  if (file_exists ($this->pidfile)) {
   echo "the file $this->pidfile exists.\n"; C3/>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-& Gt;pidfile, Getmypid ());
   Posix_setuid (self::uid);
   Posix_setgid (self::gid);
   Return (Getmypid ());
  }
 

After the program is started, the parent process is launched, the child process runs in the background, the subprocess permissions switch from root to the specified user, and the PID is written to the process ID file.

5.2. Program Stop

The program stops by simply reading the PID file and then calling Posix_kill ($pid, 9); Finally, delete the file.

 Private function Stop () {if (file_exists ($this->pidfile)) {$pid = File_get_cont
   Ents ($this->pidfile); 
   Posix_kill ($pid, 9);
  Unlink ($this->pidfile); }
 }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.