php pcntl_fork process does not die solution: 1. Open the corresponding PHP code file; 2. Check the php multi-thread processing code; 3. Pass "public function installSignal(){pcntl_signal(SIGTERM, [$ This, 'sigHandle'])...};" can be used to install the signal processor.
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, Dell G3 computer.
php What should I do if the pcntl_fork process does not die?
Problem description
The first time I used PHP multi-threaded processing tasks caused a zombie process problem, the reason was that the child process did not send the end signal and the parent process did not wait. The end of the child process
Understanding
pcntl_fork returns -1: Failed to start the process 0: Indicates that the current child process is greater than zero: The current parent Process, the return value is the child process pid
After the fork child process code is executed, it must exit() and send an end signal. Otherwise, continue to fork the child process. Get the parent process pid = posix_getppid(), current pid = getmypid() or posix_getpid()
The parent process is best to wait for the child process to finish executing and recycle the child process through pcntl_wait(), pcntl_waitpid( ) to implement synchronous and asynchronous waiting for the parent process to loop the child process:
$result = pcntl_waitpid($pid_, $status, WNOHANG); $result等于-1时代表子进程结束
The function of the signal processor is to process the end signal returned by the child process
public function run() { $this->installSignal(); // 获取当前pid getmypid() $current_pid = posix_getpid(); // dump('当前pid:'.$current_pid); cli_set_process_title('设置process_title'); $pids = []; for($i = 0; $i < $this->forks; $i ++){ $pid = pcntl_fork(); if($pid == -1){ die('进程开启失败'); }else if($pid){ // 父进程得到子进程pid dump('父进程'); dump('父进程得到子进程pid'.$pid); $pids[] = $pid; }else{ dump('子进程'); dump('父进程pid-'.posix_getppid()); // 子进程 dump("第{$i}个进程"); sleep(10); dump("第{$i}个进程:等待10s"); // 发送结束信号 // exit(-1); // posix_kill(getmypid(), SIGKILL); posix_kill(getmypid(), SIGHUP); } } // 父进程等待子进程执行结束 while($pids){ foreach($pids as $k => $pid_){ dump('父进程不阻塞-等待子进程结束'); $result = pcntl_waitpid($pid_, $status, WNOHANG); dump($result); if($result === -1){ dump('子进程返回状态'.$status); unset($pids[$k]); } } } /** * 信号处理器 */ public function sigHandle($signo) { switch ($signo) { case SIGTERM: // 处理SIGTERM信号 dump('处理SIGTERM信号'); exit; break; case SIGHUP: //处理SIGHUP信号 dump('处理SIGHUP信号'); exit(SIGHUP); break; case SIGUSR1: dump('处理SIGUSR1信号'); break; default: // 处理所有其他信号 } } /** * 安装信号处理器 * */ public function installSignal() { pcntl_signal(SIGTERM, [$this, 'sigHandle']); pcntl_signal(SIGHUP, [$this,'sigHandle']); pcntl_signal(SIGUSR1, [$this,'sigHandle']); }
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of What should I do if the php pcntl_fork process does not die?. For more information, please follow other related articles on the PHP Chinese website!