How to wait for a process to terminate (and also wait for the corresponding child processes) in PHP?

StackOverflow https://stackoverflow.com/questions/8424961

  •  29-10-2019
  •  | 
  •  

سؤال

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.

لا يوجد حل صحيح

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top