duanlu2935 2013-07-16 12:33
浏览 50
已采纳

如何开始和结束新的PHP进程?

I am trying to use a pcntl extetntion for PHP to run some methods of my CLI class in a new thread. I wrote a small test method:

private function startProcess($data)
{
    $this->log('Start a child process');

    $pid = pcntl_fork();

    if($pid == -1)
        $this->log('Could not fork');
    elseif($pid)
        pcntl_wait($status);
    else {
        $this->process($data);
        sleep(10);
        posix_kill(posix_setsid(), SIGTERM);
    }
}

This method is called 10 times. $this->process($data); just prints the data in the console. As i understood it should start 10 processes and print my data, after it exit. But instead i get to wait 10 seconds for each message. Where i'm wrong?

  • 写回答

1条回答 默认 最新

  • dongwen7423 2013-07-16 12:38
    关注

    You are waiting for each process to complete immediately after starting it. If you really want to run 10 at a time, don't wait until you started all 10.

    for($i = 0; $i < 10; $i++)
        startProcess(...);
    
    for($i = 0; $i < 10; $i++)
        pcntl_wait($status);
    
    private function startProcess($data)
    {
        $this->log('Start a child process');
    
        $pid = pcntl_fork();
    
        if($pid == -1)
            $this->log('Could not fork');
        elseif(!$pid) {
            $this->process($data);
            sleep(10);
            posix_kill(posix_setsid(), SIGTERM);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 根据企业名称 对照两个文件 样本筛选/匹配
  • ¥15 Linux环境下CA证书更新问题
  • ¥15 sqlserver语句提取结果以外数据
  • ¥60 微信小程序如何上传QQ聊天文件
  • ¥300 开发的系统遭到无良商家的破解,请问如何防止再次发生,并追回损失
  • ¥15 java代码写在记事本上后在cmd上运行时无报错但又没生成文件
  • ¥15 关于#python#的问题:在跑ldsc数据整理的时候一直抱这种错误,要么--out识别不了参数,要么--merge-alleles识别不了参数(操作系统-linux)
  • ¥15 PPOCRLabel
  • ¥15 混合键合键合机对准标识
  • ¥100 现在不懂的是如何将当前的相机中的照片,作为纹理贴图,映射到扫描出的模型上