0) { } else { $pid = getmypid(); pcntl_signal(SIGTERM, 'sig_handler'); call_user_func($callback); exit(0); } array_push($processes, $pid); } function sig_handler(){ exit(0); } addTask($processes, array('test', 'run')); addTask($processes, array('test', 'run')); addTask($processes, array('test', 'run')); addTask($processes, array('test', 'run')); addTask($processes, array('test', 'run')); $runnings = 1; while($runnings > 0){ foreach( $processes AS $key => $pid ){ $res = pcntl_waitpid($pid, $status, WNOHANG | WUNTRACED); if ($res === -1) { $log = "pcntl_waitpid failed. the process maybe available"; error_log( $log ); } elseif ($res === 0) { continue; } else { if (pcntl_wifsignaled($status)) { $term_signal = pcntl_wtermsig($status); $log = sprintf('子进程异常终止信号:%s, PID:%s', $term_signal, $pid); error_log( $log ); } if (pcntl_wifstopped($status)) { $stop_signal = pcntl_wstopsig($status); $log = sprintf('子进程异常停止信号:%s, PID:%s', $stop_signal, $pid); error_log( $log ); } // for PHP 5 >= 5.3.4 // if (pcntl_wifexited($status)) { // $errno = pcntl_wexitstatus($status); // $errmsg = pcntl_strerror($errno); // $log = sprintf('子进程异常退出:[%s]%s, PID:%s', $errno, $errmsg, $pid); // error_log( $log ); // } else { // $errno = pcntl_get_last_error(); // $errmsg = pcntl_strerror($errno); // $log = sprintf('子进程异常退出:[%s]%s, PID:%s', $errno, $errmsg, $pid); // error_log( $log ); // } unset($processes[$key]); $runnings = count($processes); } } usleep(100); } class test{ function run($sec = 30){ //$sec = mt_rand(1,$sec); sleep($sec); echo getmypid() . ':done => ' . $sec . PHP_EOL; } }