Search code examples
phpphp-7php-5.6pcntl

PHP - Issue with pcntl in PHP 7.0+. Potential bug


I have encountered an issue with the pcntl signal handling i PHP 7.0+. The problem is that alarms aren't getting scheduled in some cases.

The following example works in PHP 5.6 but neither in PHP 7.0 or 7.1.

file.php

require_once('file2.php');

declare(ticks = 1);

// Add an alarm listener
pcntl_signal(SIGALRM, function() {
    var_dump("Triggered");

    // Re-schedule the alarm
    pcntl_alarm(5);
});

// Schedule the initial alarm
pcntl_alarm(5);

test();

file2.php

function test() {
    while(true) {
        sleep(2);
    }
}

Snippet working in both PHP 5.6 and 7.0+. If we combine the code into one file then it is working.

declare(ticks = 1);

// Add a alarm listener
pcntl_signal(SIGALRM, function() {
    var_dump("here");

    // Re-schedule the alarm to be triggered
    pcntl_alarm(5);
});

// Set the initial alarm
pcntl_alarm(5);

function test() {
    while(true) {
        sleep(2);
    }
}

test();

Solution

  • The issue is related to https://bugs.php.net/bug.php?id=71448#1463246578.

    pcntl_async_signals() which was introduced in 7.1 solves the issue.