php守护进程demo

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();
posted @ 2022-03-04 14:59  alwayslinger  阅读(54)  评论(0编辑  收藏  举报