php forking issue

混江龙づ霸主 提交于 2019-12-02 08:15:40

Just use pcntl_wait(). There's no need to see if the child process has finished, just call pcntl_wait() and block until the child is reaped.

Avoid passing WNOHANG so that your parent process will sit and wait for a child to finish.

You can replace the reaping code you've written (starting at line 58 '$q=true;' of your example) with this:

$status = null;

do {
    // You can use $status with pcntl_wifexited(), pcntl_wifstopped(),
    // pcntl_wifsignaled(), pcntl_wexitstatus(), pcntl_wtermsig() and
    // pcntl_wstopsig() if you need to.

    $pid = pcntl_wait($status);

} while ($pid > 0);

Fork in foreach:

<?
declare(ticks=1);
pcntl_signal(SIGUSR1, create_function('$signo', 'sleep(1);while (($pid=pcntl_wait(@$status, WNOHANG))>0) {}'));//protect against zombie children
foreach ($tasks as $v)
        {if (($pid=pcntl_fork())===-1)
            {//...
             continue;
            }
         else if ($pid===0)
              {ob_start();//prevent output to main process
               register_shutdown_function(create_function('$pars', 'ob_end_clean();posix_kill(posix_getppid(), SIGUSR1);posix_kill(getmypid(), SIGKILL);'), array());//to kill self before exit();, or else the resource shared with parent will be closed
               //...
               exit();//avoid foreach loop in child process
              }
        }
?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!