Two common implementation methods of the PHP daemon are described in detail.

Source: Internet
Author: User

Two common implementation methods of the PHP daemon are described in detail.

This article describes two common implementation methods of the PHP daemon. We will share this with you for your reference. The details are as follows:

Method 1: Use nohup and & together.

Add the & Symbol after the command to enable the startup process to run in the background without occupying the console. The console can run other commands. Here I will use a while loop for demonstration, the Code is as follows:

<?phpwhile(true){    echo time().PHP_EOL;    sleep(3);}

Start the process in & Mode

[root@localhost php]# php deadloop.php &[1] 3454[root@localhost php]# ps aux | grep 3454root   3454 0.0 0.8 284544 8452 pts/0  T  18:06  0:00 php deadloop.phproot   3456 0.0 0.0 103316  896 pts/0  S+  18:08  0:00 grep 3454[1]+ Stopped         php deadloop.php[root@localhost php]#

We can see that the process does not occupy the console, and the console can run other commands. At this time, we can also use the fg command to restore the process to the normal mode of using the console.

[root@localhost php]# fgphp deadloop.php1470996682147099668514709966881470996691

The above is a brief introduction to & commands

Next let's take a look at another command nohup.

When nohup is added before the command, the startup process will ignore the linux SIGHUP signal. Under what circumstances will the SIGHUP signal be triggered in linux? The following content is taken from Baidu Encyclopedia:

SIGHUP will be sent to the corresponding process in the following three cases:

1. When the terminal is closed, the signal is sent to the first process of the session and the process submitted as a job (that is, the process submitted with the & symbol)
2. When the first process of the session exits, the signal is sent to each process in the foreground Process Group of the session.
3. If the parent process exits and the process becomes an orphan process group, the process in the process group is in the stopped state (receiving the SIGSTOP or SIGTSTP signal ), the signal is sent to every process in the process group.

Combined with steps 1 and 2, we know that no matter whether or not the processes started in the & (job mode) mode will receive the SIGHUP signal when the terminal is closed, what will happen if the process receives the SIGHUP signal, this is also a sentence taken from Baidu encyclopedia.

The system processes the SIGHUP signal by default and terminates the process that receives the signal. Therefore, if the program does not capture the signal, the process will exit when it receives the signal.

That is to say, the terminal process will receive the SIGHUP signal, and the default Processing Method of the signal is to end the process. Of course, we can also process the signal ourselves or ignore it, this is also an example of the above loop. We have made some improvements.

<? Phpdeclare (ticks = 1); pcntl_signal (SIGHUP, function () {// you can simply write a log to file_put_contents('logs.txt ', 'pid: '. posix_getpid (). 'receive SIGHUP sign '. PHP_EOL) ;}); while (true) {echo time (). PHP_EOL; sleep (3 );}

We don't need to be so troublesome. We only need to use the nohup Command provided to us by linux. However, when we use nohup to start the process and close the terminal, the process will ignore the SIGHUP signal and will not exit, first, remove the signal processing code. Then nohup runs.

[root@localhost php]# nohup php deadloop.php

Nohup: ignore input and append output to "nohup. out"

By default, nohup redirects program output to the nohup. out file in the current directory. If you do not have the write permission, write $ homepath/nohup. out.

[root@localhost php]# lscmd.sh deadloop.php getPhoto.php nohup.out pics[root@localhost php]# tail -f nohup.out14709997721470999775147099977814709997811470999784147099978714709997901470999793147099979614709997991470999802

At this time, the terminal is closed, and the process will not end, but become an orphan process (ppid = 1), because the parent process that created it exits.

[root@localhost ~]# ps -ef | grep 3554root   3554 3497 0 19:09 pts/0  00:00:00 php deadloop.phproot   3575 3557 0 19:10 pts/1  00:00:00 grep 3554[root@localhost ~]# ps -ef | grep 3554root   3554   1 0 19:09 ?    00:00:00 php deadloop.phproot   3577 3557 0 19:10 pts/1  00:00:00 grep 3554[root@localhost ~]#

Conclusion:Therefore, when we combine nohup and &, The started process does not occupy the console or rely on the console. After the console is closed, the process is adopted by process 1 and becomes an orphan process, this is very similar to the mechanism of the daemon.

[root@localhost php]# nohup php deadloop.php >logs.txt 2>error.txt &[1] 3612[root@localhost php]# ps -ef |grep 3612root   3612 3557 0 19:18 pts/1  00:00:00 php deadloop.phproot   3617 3557 0 19:19 pts/1  00:00:00 grep 3612[root@localhost php]#

Among them,> logs.txt redirection standard output, 2> error.txt redirection standard error output.

The above is an introduction to the first implementation method.

The second method is to implement it through code based on the rules and features of the daemon process.The main feature of the daemon is that the daemon is separated from the user terminal and session. The following is the implementation code, and the key is commented out.

<? Php $ pid = pcntl_fork (); if ($ pid =-1) {throw new Exception ('fork subprocess failed');} elseif ($ pid> 0) {// The parent process exits, the child process becomes an orphan process, and the process is adopted by process 1. The process leaves the terminal exit (0);} // The most important step, disconnects the process from the previous session, terminal, and process group control posix_setsid (); // modify the working directory of the current process because the child process inherits the working directory of the parent process, modify the working directory to release the occupation of the working directory of the parent process. Chdir ('/');/** through the previous step, we created a new session leader, the process leader, and left the terminal. However, the session leader can apply to reopen a terminal, to avoid * this situation, we create a sub-process again and exit the current process, so that the running process is no longer the session leader. */$ Pid = pcntl_fork (); if ($ pid =-1) {throw new Exception ('fork subprocess failed');} elseif ($ pid> 0) {// exit the parent process again, and the child process becomes the final daemon exit (0);} // close the standard input and output because the daemon does not use the standard input and output, error output descriptor fclose (STDIN); fclose (STDOUT); fclose (STDERR);/** Process Business Code */while (TRUE) {file_put_contents('log.txt ', time (). PHP_EOL, FILE_APPEND); sleep (5 );}

That's all!

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.