PHP Advanced Programming Example: Writing daemons, programming instance daemons
1. What is daemon process
Daemons are processes that are detached from the terminal and run in the background. The daemon is detached from the terminal to prevent the information in the process from being displayed on any terminal and the process will not be interrupted by terminal information generated by any terminal.
Like Apache, Nginx, and MySQL are daemons.
2. Why the daemon is being developed
Many programs exist in the form of services, and he has no terminal or UI interaction, and it may interact with other programs in other ways, such as TCP/UDP sockets, UNIX sockets, FIFO. Once the program is started, it goes backstage until the condition is met and he begins to process the task.
3. When to use daemons to develop applications
Take my current needs as an example, I need to run a program, and then listen to a port, continue to accept data initiated by the server, and then analyze the data processing, and then write the results into the database; I use ZEROMQ to achieve data transmission and dispatch.
If I do not adopt the Daemon way to develop the program, the program once run will occupy the current terminal window frame, and is affected by the current terminal keyboard input, there may be a program mistakenly quit.
4. Security issues with Daemons
We want the program to run in a non-superuser, so that once the program is compromised by hackers, the attacker can only inherit the permissions of the operation and not gain superuser privileges.
We want the program to run only one instance, not to run a colleague to open more than two programs, because there will be port conflicts and so on.
5. How to Develop daemons
Example 1. daemon Example
<?phpclass 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;p ort= $dbport;d bname= $dbname", $dbuser, $dbpass, Array (/* pdo::mysql_a Ttr_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 __constr UCT ($msg) {$trades = Explode (",", $msg); $this->data = $trades; Print_r ($trades); Public Function Run () {# $this->worker->logger->log ('%s executing in Thread #%lu ', __class__, $thisWorker->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 = +; 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 ()); }} 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); The Public function main ($ARGV) {if (count ($ARGV) < 2) {printf ("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 Startup
Here's the code that goes backstage after the program starts
The process ID file to determine the current process state, if the process ID file exists to indicate that the program is running, through code file_exists ($this->pidfile) implementation, but then the process is killed need to manually delete the file to run
Private Function Daemon () { if (file_exists ($this->pidfile)) { echo "the file $this->pidfile exists.\n"; C2/>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 is rolled out, the child process runs in the background, the child process permissions are switched from root to the specified user, and the PID is written to the process ID file.
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); } }
Will PHP advanced programming involve Java
Very advanced will be involved. Because Java can do a lot of things.
The production idea and application of PHP daemon the need for a team to have a long-term cooperation but no money to take only points
Recommended use Ignore_user_abort specific ideas private chat long-term cooperation can be but time is a little tight
http://www.bkjia.com/PHPjc/873340.html www.bkjia.com true http://www.bkjia.com/PHPjc/873340.html techarticle PHP Advanced Programming Example: Writing daemon, programming instance Daemon 1. What is a daemon daemon is a process that is out of the terminal and running in the background. Daemon out of the terminal ...