PHP advanced programming example: compile the daemon and programming the instance daemon _ PHP Tutorial

Source: Internet
Author: User
PHP advanced programming example: write the daemon and program the instance daemon. PHP advanced programming example: write the daemon process and program the instance daemon process 1. what is the daemon process that is out of the terminal and runs in the background. The daemon is separated from the terminal PHP advanced programming instance: write the daemon and program the instance daemon.

1. what is a daemon?

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

For example, apache, nginx, and mysql are all daemon processes.

2. why the development daemon process?

Many programs exist in the form of services. 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. Once started, the program enters the background until it meets the conditions and starts to process the task.

3. when to use a daemon process to develop applications

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

If I do not use a daemon to develop the program, the program will occupy the current terminal window once it runs, and may be affected by the keyboard input of the current terminal. The program may exit by mistake.

4. daemon security issues

We want the program to run on non-super users. Once the program is controlled by hackers due to a vulnerability, attackers can only inherit the operation permission, but cannot obtain the super user permission.

We hope that the program can run only one instance without running more than two programs, because there may be port conflicts and other problems.

5. how to develop daemon

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 = '2017. 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; 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 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 ignore (ticket, login, volume, 'status') VALUES (: ticket,: login,: volume, 'n') "; $ Something = $ dbh-> prepare ($ insert ); $ Something-> bindValue (': ticket', $ this-> data [0]); $ Something-> bindValue (': login ', $ this-> data [1]); $ Something-> bindValue (': volume', $ this-> data [2]); $ Something-> execute (); $…… = null ;/*...... */$ update = "UPDATE into SET 'status' = 'y' WHERE ticket =: ticket and 'status' = 'n '"; $ Something = $ dbh-> prepare ($ update); $ Something-> bindValue (': ticket', $ this-> data [0]); $ Something-> execute (); // echo $ Something-> 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 processing and echoing back */while ($ message = $ this-> zmq-> recv ()) {// print_r ($ message); // if ($ trades) {$ this-> pool-> submit (new transfer ($ 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 startup

The following code enters the background after the program is started:

The current process status is determined by the process ID File. if the process ID file exists, it indicates that the program is running and implemented through the code file_exists ($ this-> pidfile, however, if the process is killed, you need to manually delete the file before it can 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 released, and the child process will run in the background. the sub-process permission will be changed from root to the specified user, and the pid will be written to the process ID file.

5.2. program stopped

When the program stops, you only need to read the pid file and then call posix_kill ($ pid, 9) to delete the file.

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. Because Java can do too much.

PHP daemon production ideas and applications in urgent need of a team can work together for a long time, but there is no money to get only points

It is recommended that you use ignore_user_abort to talk about long-term cooperation.

Secrets 1. what is a daemon? daemon is a process that is detached from the terminal and runs in the background. Daemon is out of the terminal...

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.