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,
-
I run this program in shell (CLI), and not related to CGI functions. So I won’t need to worry about max_execution_time.
-
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.
-
The python program I want to call may hang for very long time, so I want to check timeout and terminate it.
proc_get_status can get pid of child process
then you can use
pcntl_waitpidto wait until the child process exitBut you need to have your php compiled with
pcntlextension.See PCNTL Functions
UPDATE: If you want to kill child process after a timeout
First: install a
SIGALARMhandler in your main processSecond: use
pcntl_alarmto send a alarm signal after secondsFor 2nd question,
proc_terminatewill work no matter what process be opend.