守护进程是一类在后台运行的特殊进程,用于执行特定的系统任务。

很多守护进程在系统引导的时候启动,并且一直运行直到系统关闭。

守护进程一直在后台运行,脱离终端运行的程序 独立运行的守护进程。

<?php。
class myProcess
{
    const UID = 80;
    const GID = 80;
    protected $loop = true;
    protected $pidFile = "/tmp/myprocess.pid";
    //protected $data = "123132132\r\n";

    private function checkPidFile()
    {
        if(file_exists($this->pidFile))
        {
            echo "daemon process is already runing.\n";
            exit();
        }
    }
    private function daemon()
    {
    
        $pid = pcntl_fork();
        if ($pid == -1)
        {
            exit("fork fail");
        }else if($pid == 0){
            $this->handler();
        }else{
            exit();
        }
    }

    private function handler()
    {
        posix_setsid();
        posix_setuid(self::UID);
        posix_setgid(self::GID);
        #fclose(STDIN);  
        #fclose(STDOUT);  
        #fclose(STDERR); 
        #$pid = posix_getpid
        $pid = getmypid();
        file_put_contents($this->pidFile, $pid); #or die("open file fail");
    }


    private function start()
    {
        pcntl_signal_dispatch();
        $this->checkPidFile();
        $this->daemon();
        while ($this->loop) {
            $id = getmypid();
            //$f = fopen("/tmp/a.txt",a);
            //fwrite($f,$this->data);
            //file_put_contents("/tmp/".$id.".log","进程ID:$id 正常运行\r\n");
            sleep(1);
        }
    }

    private function stop()
    {
        if (file_exists($this->pidFile)) {
           $pid = file_get_contents($this->pidFile);
           posix_kill($pid, SIGHUP);
           unlink($this->pidFile);
           echo "stop success.....";
        }else{
            echo "stop fail, daemon process not is already runing";
        }
    }

    private function restart()
    {
        $this->stop();
        $this->start();    
    }

    public function reload()
    {
        // $this->loop = false;
        // pcntl_signal_dispatch();
        // $this->loop = true;
        // $this->start();
    }

    public function main($argv)
    {
        switch ($argv[1]) {
             case 'start':
               $this->start();
               break;
             case 'stop':
                  $this->stop();
                  break;
            case 'restart':
                  $this->restart();
                  break;
            case 'reload':
                  $this->reload();
                  break;
             default: 
                 echo 'php process.php start | stop | restart | reload';
                 exit;
        }
    }

}

$proce = new myProcess();
$proce->main($argv);