// 写入文件
public function write($txt){
$filename = "example.txt";
$file = fopen($filename, "a") or die("Unable to open file!");
fwrite($file, $txt."\n");
fclose($file);
}
//启动守护进程
public function daemonStart() {
pcntl_signal(SIGCHLD, SIG_IGN); // 忽略子进程退出信号
$pid = pcntl_fork();
if ($pid == -1) {
die('无法启动子进程');
} elseif ($pid) {
// 父进程(第一层)等待子进程(第二层)退出
pcntl_wait($status);
exit;
}
// 子进程(第二层)继续 fork
$pid2 = pcntl_fork();
if ($pid2 == -1) {
die('无法启动孙子进程');
} elseif ($pid2) {
// 子进程(第二层)直接退出,孙子进程(第三层)由 init 接管
posix_kill(getmypid(), SIGTERM); // 终止子进程
exit;
}
// 孙子进程(第三层)作为守护进程运行
while (true) {
sleep(1);
$this->write(getmypid() . ':time:' . date('Y-m-d H:i:s') . PHP_EOL);
$file = file_get_contents('./test.txt');
if ($file != 1) {
posix_kill(getmypid(), SIGTERM); // 终止子进程
exit(1);
}
}
}