今天我遇到了一些奇怪的PHP行为:
当分叉时,每个孩子都应该触发__destruct函数,但是在最后一个孩子完成之后,父母不再需要调用__destruct!
我的代码:
class Test {
public function __construct() {
for ($i = 0; $i < 4; $i++) {
$pid = pcntl_fork();
if (!$pid) {
print("child ".$i."\n");
exit($i);
}
while (pcntl_waitpid(0, $status) != -1) {
$status = pcntl_wexitstatus($status);
print("child ".$status." finished\n");
}
print("parent still alive\n");
}
}
public function __destruct() {
print("destruct\n");
}
}
这会将以下内容打印到我的debian shell中:
child 0
destruct
child 0 finished
child 1
destruct
child 1 finished
child 2
destruct
child 2 finished
child 3
destruct
child 3 finished
parent still alive
我该如何解决这个问题?我做错了什么?