graceful stop of php script

Today I’d like to tell you how I implemented graceful stop of php script.

Problem

We have some daemon script that handles some task. The problem that it’s in memory and in order to update it we need to restart it. The problem is such stop could lead to data missing. So we need to finish current task and only after that stop the script.

Solution

Php has pcntl_signal function that could catch signal from OS and then handle it.


class HandleEventsFromQueueCommand extends \om\console\Command
{

    private static $_stop = false;

    public function actionIndex()
    {
        $this->checkExit();

        while (true) {
            if (self::$_stop) {
                break;
            }
            // handle our events here
        }
    }

    private function checkExit()
    {
        if (!function_exists('pcntl_signal')) {
            return ;
        }
        $handler = function ($sigNumber) {
            if ($sigNumber == SIGTERM || $sigNumber == SIGHUP || $sigNumber == SIGINT){
                $this->_verbose("Process: " .getmypid() . " got signal $sigNumber and will exit.");
                self::$_stop = true;
            }
        };

        pcntl_signal(SIGTERM, $handler);
        pcntl_signal(SIGHUP,  $handler);
        pcntl_signal(SIGINT, $handler);
    }

}

It’s straightforward – catch exit signal and set flag inside your script that it’s time to stop.

Leave a Reply

Your email address will not be published. Required fields are marked *