Skip to content

How to implement a daemon in PHPΒΆ

PHP can be used to implement a Linux daemon - which is a process which gets started by init or systemd and will continue running until it gets a signal like SIGHUP to stop again (or pressing ^C in a console). This is possible because PHP also contains support for signal handling.

The following example includes handling of forks created by pcntl_fork():

#!/usr/bin/php
<?php
class Service
{
    protected $input;
    protected $output;
    protected $run;

    /**
     * Handle signals
     */
    public function signalHandler($signal, $info): void
    {
        if (SIGCHLD === $signal) {
            // Clean up child processes
            $pid = pcntl_waitpid(-1, $status, WNOHANG);
            while ($pid > 0) {
                $exitCode = pcntl_wexitstatus($status);
                $pid = pcntl_waitpid(-1, $status, WNOHANG);
            }
        } else {
            $this->run = false;
        }
    }

    /**
     * Main run loop
     */
    public function run(): int
    {
        pcntl_signal(SIGTERM, [$this, 'signalHandler']);
        pcntl_signal(SIGHUP, [$this, 'signalHandler']);
        pcntl_signal(SIGINT, [$this, 'signalHandler']);
        pcntl_signal(SIGCHLD, [$this, 'signalHandler']);

        $this->run = true;
        declare(ticks = 1) {
            while ($this->run) {
                sleep(5);

                // Do something every 5 seconds
                // Here you could also start a new child process using pcntl_fork() if needed
            }
        }

        return 0;
    }
}

$service = new Service();
return $service->run();