Generally, Server programs run in the system background, which is very different from common interactive command line programs.
Generally, Server programs run in the system background, which is very different from common interactive command line programs. There is a function daemon in glibc. By calling this function, the current process can be detached from the terminal into a daemon. For more information, see man daemon. This function is not available in PHP for the time being. if you are interested, you can write a PHP extension function.
The PHP command line program provides three daemon methods:
1. use nohup
nohup php myprog.php > log.txt &
Daemon is implemented here.
Execute php myprog. php separately. when ctrl + c is pressed, the program execution will be interrupted and the current process and sub-processes will be killed.
Php myprog. php &. in this way, although the execution program is also converted to backend running, it is actually dependent on the terminal, and the process will be killed when the user exits the terminal.
II. use PHP code to implement
Function daemonize () {$ pid = pcntl_fork (); if ($ pid =-1) {die ("fork (1) failed! \ N ");} elseif ($ pid> 0) {// let the process started by the user exit (0 );} // create a new session different from the terminal to detach the terminal posix_setsid (); $ pid = pcntl_fork (); if ($ pid =-1) {die ("fork (2) failed! \ N ");} elseif ($ pid> 0) {// the parent process exits, and the child process becomes the final independent process exit (0) ;}} daemonize (); sleep (1000 );
Use the above code to implement daemonize () daemonize. when your PHP program needs to be converted to the background for running, you only need to call the encapsulated function daemonize.
Note: the redirection of standard input and output is not implemented here.
3. use swoole to implement
The process module provided by swoole extension is used to replace the pcntl extension of PHP and solve many problems of pcntl. Like deamon, swoole can achieve the goal through a function. For more information about swoole_process, see the original article.
Conclusion: Why is the cover image a fork. Pai_^