我有這個代碼塊,它可以在我的各種php cli程序中完美地滿足我的需求。除了有時一個孩子會成爲殭屍。PHP分叉:當它變成殭屍時殺死孩子
我的問題是在哪裏放置代碼來檢查一個孩子是否跑5分鐘,如果它是更長的然後殺死它?
我知道posix_kill殺死它,以及如何跟蹤它。 There are examples of taskmanagers here。我不確定如何將這些新功能組合到代碼中。每次我嘗試,我都陷入一片混亂。也許有人知道分叉可以修復我的代碼?
忽略所有的error_logs - 我喜歡看它運行時發生了什麼。
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;
}
}
}
真棒標題... – 2012-02-06 19:43:01
孩子們成爲殭屍,因爲他們還沒有收穫,不是因爲他們還活着...... – 2012-02-06 19:52:08
@Ignacio - 有實例說,我通過捲曲檢查代理。有時候這個孩子變得沒有反應,因爲Curl已經變得沒有了,然後如果我早晚檢查1000個代理,我的孩子們都會被殭屍化。所以這就是我需要知道他們已經跑了多久的一個例子,所以我可以殺死他們並且生下新的孩子。 – PaulM 2012-02-07 09:40:22