General server programs are running in the background of the system, which is very different from ordinary interactive command-line programs. There is a function daemon in the glibc. Calling this function allows the current process to be detached from the terminal into a daemon, as described in Man daemon. PHP does not have this function temporarily, of course, if you are interested, you can write a PHP extension function to achieve.
There are 2 ways to implement daemons for PHP command-line programs:
First, the use of nohup
copy code code as follows:
nohup php myprog.php > Log.txt &
The daemon is implemented here.
The PHP myprog.php is executed separately, and when CTRL + C is pressed, the program execution is interrupted, and the current process and the child process are kill.
PHP myprog.php, so that the execution of the program, although also into the background running, is actually dependent on the terminal, when the user quit the terminal process will be killed.
Second, the use of PHP code to achieve
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
function Daemonize () {$pid = Pcntl_fork (); if ($pid = = 1) {die ("fork (1) failed!n");} elseif ($pid > 0) {//Let user initiated Process exit exit (0); Establish a new session that is different from the terminal to get rid of the terminal posix_setsid (); $pid = Pcntl_fork (); if ($pid = = 1) {die ("fork (2) Failed!n");} elseif ($pid > 0) {//parent process exits, leaving child process as final standalone process exit (0);} Daemonize (); Sleep (1000); |
With the above code can be implemented daemon, when your PHP program needs to switch to the background to run, only need to call a good package function daemonize () can be.
Note: There is no redirection to achieve standard input/output.