PHP守护进程demo
<?php
class Daemon
{
private Closure $call;
public function __construct(Closure $call)
{
$this->call = $call;
$this->prepareDaemon();
}
private function prepareDaemon(): void
{
umask(0);
if ($sid = pcntl_fork()) {
exit();
}
posix_setsid();
if ($did = pcntl_fork()) {
exit();
}
chdir('/');
// 断开终端
fclose(STDIN);
fclose(STDOUT);
fclose(STDERR);
fopen('/dev/null, "a");
fopen('/dev/null', "a");
fopen('/dev/null', "a");
}
public function start(): void
{
call_user_func($this->call);
}
}
$c = function () {
sleep(100);
};
(new Daemon($c))->start();