在下面的代码中。我想了解这种行为。
class ForkManager
{
private $_max_workers = 3;
private $_open_processes = 0;
private $_tasks = array();
public function setMaxWorkers($num)
{
$this->_max_workers = $num;
}
public function addTask($command)
{
$this->_tasks[] = $command;
}
public function execute()
{
while($this->_tasks) {
$command = array_shift($this->_tasks);
$pid = pcntl_fork();
if(!$pid) {
/* Execute in child process start */
echo "$command\n";
exec($command, $return, $out);
exit(0);
/* Execute in child process end */
} else {
++$this->_open_processes;
//var_dump($this->_open_processes, $this->_max_workers);
if($this->_open_processes >= $this->_max_workers) {
(pcntl_wait($status));
--$this->_open_processes;
}
}
}
}
public function getOpenProcess()
{
return $this->_open_processes;
}
public function isAllTaskCompleted()
{
return $this->_open_processes;
}
}
class Scheduler {
public function __construct() {
var_dump("Waking up...");
}
private function getTasksForCurrentHour() {
//static for now
return array(
'startmusic',
'logintohris',
'checkforerrorsemail',
'startcoffeemachine'
);
}
public function run() {
$fm = new ForkManager();
$tasks = $this->getTasksForCurrentHour();
foreach ($tasks as $key => $task) {
$fm->addTask('php UnversalWorker.php ' . $task);
}
$fm->execute();
}
public function __destruct() {
var_dump("All tasks done... Going to sleep for an hour");
}
}
$s = new Scheduler();
$s->run();
现在,根据我的代码输出应该是
string(12) "Waking up..."
php UnversalWorker.php startmusic
php UnversalWorker.php logintohris
php UnversalWorker.php checkforerrorsemail
php UnversalWorker.php startcoffeemachine
string(44) "All tasks done... Going to sleep for an hour"
但实际输出是
string(12) "Waking up..."
php UnversalWorker.php startmusic
php UnversalWorker.php logintohris
php UnversalWorker.php checkforerrorsemail
string(44) "All tasks done... Going to sleep for an hour"
php UnversalWorker.php startcoffeemachine
string(44) "All tasks done... Going to sleep for an hour"
string(44) "All tasks done... Going to sleep for an hour"
string(44) "All tasks done... Going to sleep for an hour"
string(44) "All tasks done... Going to sleep for an hour"
似乎每个子进程都调用父进程的析构函数,即Scheduler类。我想知道这是默认行为吗?如果是,那么任何特殊原因。如果不是,那么我的实现中肯定会有一些错误。任何人都可以指出这一点。