jfra jfra - 3 months ago 79
PHP Question

PHP CLI pcntl not working in PHP7.0 Ubuntu xenial server

I'm using this script in PHP 5.5.9:

declare(ticks = 1);

pcntl_signal(SIGTERM, array($this, 'stopSending'));
pcntl_signal(SIGINT, array($this, 'stopSending'));
pcntl_signal(SIGUSR1, array($this, 'stopSending'));
pcntl_signal(SIGUSR2, array($this, 'stopSending'));
pcntl_signal(SIGQUIT, array($this, 'stopSending'));
pcntl_signal(SIGHUP, array($this, 'stopSending'));

public function stopSending($signals)
{
echo "hello";
exit();
}

while (true) {
// some logic
}


In Ubuntu 14 that works fine, but when try to execute in Ubuntu 16.04 with PHP7.0 and try to send signal (kill PID), PHP CLI doesn't stop and keep runnig.

In Ubuntu 16.04 i check for pcntl extension, and that is ok:

>php -m | grep pcntl
pcntl


I do not get any errors when I run, but neither stops (or display echo).

Is there a problem with PHP7 and pcntl?

UPDATE

The problem is when encapsulate the while loop into function:

function start()
{
while (true) {
// some logic
}
}

declare(ticks = 1);

pcntl_signal(SIGTERM, "stopSending");
pcntl_signal(SIGINT, "stopSending");
pcntl_signal(SIGUSR1, "stopSending");
pcntl_signal(SIGUSR2, "stopSending");
pcntl_signal(SIGQUIT, "stopSending");
pcntl_signal(SIGHUP, "stopSending");

function stopSending($signals)
{
echo "hello";
exit();
}

start();


This code does not stop.

Answer

There is a good explanation about PHP signal handling here. So the best way to make sure your signal handler triggers in appropriate time would be something like this:

<?php

declare(ticks = 1);

function start()
{
    while (true) {
        pcntl_signal_dispatch();
    }
}

pcntl_signal(SIGTERM, "stopSending");
pcntl_signal(SIGINT, "stopSending");
pcntl_signal(SIGUSR1, "stopSending");
pcntl_signal(SIGUSR2, "stopSending");
pcntl_signal(SIGQUIT, "stopSending");
pcntl_signal(SIGHUP, "stopSending");

function stopSending($signals)
{       
    echo "hello";
    exit();
}

start();

?>