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条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀