dongshi2588 2011-12-08 01:15
浏览 170
已采纳

如何在PHP中等待进程终止(并等待相应的子进程)?

I have a program that normally run till it terminates, but under some situations, it created two children process, and the main process then exits. The children processes will be still running after the main process exited.

I want to call this program in PHP.

Originally, I used the following strategy (not valid php code),

$process=proc_open("python xxx.py");
while (1) {
   sleep(5);
   $status = proc_get_status($process);
   if (!$status['running']) {
       exit_loop;
   }
   if (timeout) {
      proc_terminate($process, 9);
      exit_loop;
   }
}

But then I soon found the bug that the process actually exited immediately that $status['running'] is false, but the children process is still running. How to actually wait for all children processes?

2nd question is i haven't looked into the proc_terminate, but I also observed that proc_terminate may not work as I expected. Is that because the $process is a bash but not the real python process? It may also because that what I terminated is only the parent main process but not the children process.

Anyone advise me that whether the above code is robust PHP code or not? Is there any better way to deal with this?

Thanks.

======================

More info,

  1. I run this program in shell (CLI), and not related to CGI functions. So I won't need to worry about max_execution_time.

  2. I want to wait the children processes created by the main process opened by proc_open, I will only create one process in the program.

  3. The python program I want to call may hang for very long time, so I want to check timeout and terminate it.

  • 写回答

3条回答 默认 最新

  • duanqinjiao5244 2011-12-08 01:29
    关注

    proc_get_status can get pid of child process

    $status = proc_get_status($process);
    $pid = $status["pid"]
    

    then you can use pcntl_waitpid to wait until the child process exit

    pcntl_waitpid($pid, $child_status);
    

    But you need to have your php compiled with pcntl extension.

    See PCNTL Functions

    UPDATE: If you want to kill child process after a timeout

    First: install a SIGALARM handler in your main process

    function term_proc() {
       // terminate your all child process
    }
    
    pcntl_signal(SIGALARM, term_proc);
    

    Second: use pcntl_alarm to send a alarm signal after seconds

    pcntl_alarm($seconds)
    

    For 2nd question, proc_terminate will work no matter what process be opend.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?