I've got this block of code which works perfectly for my needs in my various php cli programs. Except that sometimes a child will become a zombie.
My question is where to place code to check if a child runs say for 5 minutes and if it's longer then to kill it?
I know about posix_kill to kill it and how to keep track of it. There are examples of taskmanagers here.
I am unsure how to combine these new features into the code. Everytime I attempt to, I just get into a mess. Maybe someone who knows about forking can fix my code up?
Ignore all the error_logs - I like to see what is happening when it runs.
public function __construct($data) {
//Keep track of all of the children processes
$this->children = Array();
//Specify the maximum number of child processes to fork at any given time
$this->max_children = 5;
}
private function process()
{
foreach ($collection as $stuff)
{
//FORK THE PROCESS
$pid = pcntl_fork();
//Something went wrong
if($pid == -1)
{
error_log ("could not fork");
die ();
}
//PARENT PROCESS
if($pid)
{
//error_log ("Parent: forked " . $pid);
$this->children[] = $pid;
}
//CHILD PROCESS
else
{
// Do stuff here
exit(); //Exit the child thread so it doesn't continue to process the data
}
//COLLECT ALL OF THE CHILDREN AS THEY FINISH
while( ($c = pcntl_wait($status, WNOHANG OR WUNTRACED) ) > 0)
{
//error_log ("Collected Child - " . $c);
$this->remove_thread($this->children, $c);
error_log ("children left: " . count($this->children));
}
//WAIT FOR A CHILD TO FINISH IF MAXIMUM PROCESSES IS EXCEEDED
if(sizeof($this->children) > $this->max_children)
{
//error_log ("Maximum children exceeded. Waiting...");
if( ($c = pcntl_wait($status, WUNTRACED) ) > 0)
{
//error_log ("Waited for Child - " . $c);
$this->remove_thread($this->children, $c);
error_log ("children left: " . count($this->children));
}
}
}
//COLLECT ALL OF THE CHILDREN PROCESSES BEFORE PROCEEDING
while( ($c = pcntl_wait($status, WUNTRACED) ) > 0){
//error_log ("Child Finished - " . $c);
$this->remove_thread($this->children, $c);
error_log ("children left: " . count($this->children));
}
}
//Function to remove elements from an array
private function remove_thread(&$Array, $Element)
{
for($i = 0; $i < sizeof($Array); $i++)
{
//Found the element to remove
if($Array[$i] == $Element){
unset($Array[$i]);
$Array = array_values($Array);
break;
}
}
}