php forking issue

前端 未结 2 878
春和景丽
春和景丽 2021-01-28 15:34

I have the following test php to do a fork/spawn process, where the test also attempts to kill the child process (zombie) after is completes..

I\'d like to have a more e

相关标签:
2条回答
  • 2021-01-28 16:23

    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);
    
    0 讨论(0)
  • 2021-01-28 16:29

    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
                  }
            }
    ?>
    
    0 讨论(0)
提交回复
热议问题