Home > Article > Backend Development > php后台守护进程+进程信号处理
<?phpset_time_limit(0); // 只允许在cli下面运行 if (php_sapi_name() != "cli"){ exit("只允许在cli下面运行\n"); } //第一子进程,实现与父进程的脱离$pid = pcntl_fork();if ($pid == -1) { exit("fork failed!\n");}elseif($pid > 0) { exit(0);//父进程退出}//子进程成为新的会话组长posix_setsid();//为禁止第一子进程打开控制终端,需要创建第二子进程,具体我也不清楚什么原理$pid = pcntl_fork();if ($pid == -1) { exit("fork2 failed!\n");}elseif($pid > 0) { exit(0);}echo "进程id:".posix_getpid()."\n";$open = true;function sig_handler($signo){ global $open; switch ($signo) { //自定义信号SIGUSR1 case SIGUSR1: echo "你好啊,我继续跑\n"; break; case SIGTERM: echo "等这次循环结束我就关闭\n"; $open = false; break; default: # code... break; }}pcntl_signal(SIGUSR1,'sig_handler');pcntl_signal(SIGTERM,'sig_handler');//这行代码很重要,这样每执行一条低级语句就能检查信号,否则无限循环中无法检测到进程信号declare(ticks=1);while($open){ echo date('Y-m-d H:i:s')."\n"; sleep(1);}echo "我退出了88";exit;