Current Location: Home> Latest Articles> time_nanosleep What to do if it is interrupted by an interrupt signal?

time_nanosleep What to do if it is interrupted by an interrupt signal?

gitbox 2025-05-27

In PHP, the time_nanosleep() function is used to make the program sleep for a specified time with nanosecond precision. It is very simple to use, for example:

 time_nanosleep(1, 500000000); // Sleep1.5Second

However, in actual use, time_nanosleep() may be interrupted by system signals (such as interrupt signals), causing the sleep to end early. In this case, the function returns an array containing the remaining seconds and nanoseconds, rather than boolean true .

Why is it interrupted by the signal?

In Linux or Unix systems, processes may receive various signals (such as SIGINT, SIGTERM, etc.), which will interrupt the sleep state, causing time_nanosleep() to return. PHP itself does not automatically retry sleep, which leads to inaccurate sleep time.

How to judge and recover?

When time_nanosleep() is interrupted by the signal, it does not return true , but returns an array:

 [
    'seconds' => 剩余Second数,
    'nanoseconds' => 剩余纳Second数,
]

Based on this, we can write a loop to ensure the complete sleep time, i.e.:

 function reliable_nanosleep(int $seconds, int $nanoseconds): void {
    while (true) {
        $result = time_nanosleep($seconds, $nanoseconds);
        if ($result === true) {
            // Sleep completed successfully
            break;
        }
        // Interrupted by signal,$result Includes the remaining time
        $seconds = $result['seconds'];
        $nanoseconds = $result['nanoseconds'];
    }
}

This function keeps retrying the remaining sleep time until the full sleep is complete.

Complete sample code

 <?php
function reliable_nanosleep(int $seconds, int $nanoseconds): void {
    while (true) {
        $result = time_nanosleep($seconds, $nanoseconds);
        if ($result === true) {
            break;
        }
        $seconds = $result['seconds'];
        $nanoseconds = $result['nanoseconds'];
    }
}

// Example:Sleep2.3Second
echo "开始Sleep\n";
reliable_nanosleep(2, 300000000);
echo "Sleep结束\n";
?>

Additional advice

  • Signal processing : If your program needs to process signals, it is recommended to set the signal processing function in combination with pcntl_signal() to manage interrupt behavior more reasonably.

  • Alternative : If your system environment supports usleep() or sleep() , they can also be used, but they have lower precision.


For more PHP related information, please refer to gitbox.net/php-docs for detailed documents and examples.