I have this block of code that works great for my needs in my various php cli programs. Except that sometimes a child becomes a zombie.
My question is where to place the code to check if the child is working for 5 minutes, and if it is longer than to kill it?
I know about posix_kill to kill it and how to track it. There are examples of task managers .
I am not sure how to combine these new features into code. Every time I try, I just get in a mess. Maybe someone who knows about forking can fix my code?
Ignore all error_logs - I like to see what happens when it runs.
public function __construct($data) {
$this->children = Array();
$this->max_children = 5;
}
private function process()
{
foreach ($collection as $stuff)
{
$pid = pcntl_fork();
if($pid == -1)
{
error_log ("could not fork");
die ();
}
if($pid)
{
$this->children[] = $pid;
}
else
{
exit();
}
while( ($c = pcntl_wait($status, WNOHANG OR WUNTRACED) ) > 0)
{
$this->remove_thread($this->children, $c);
error_log ("children left: " . count($this->children));
}
if(sizeof($this->children) > $this->max_children)
{
if( ($c = pcntl_wait($status, WUNTRACED) ) > 0)
{
$this->remove_thread($this->children, $c);
error_log ("children left: " . count($this->children));
}
}
}
while( ($c = pcntl_wait($status, WUNTRACED) ) > 0){
$this->remove_thread($this->children, $c);
error_log ("children left: " . count($this->children));
}
}
private function remove_thread(&$Array, $Element)
{
for($i = 0; $i < sizeof($Array); $i++)
{
if($Array[$i] == $Element){
unset($Array[$i]);
$Array = array_values($Array);
break;
}
}
}
Paulm source
share