note 124049 added to function.pcntl-signal
| From: | kuba at valentine dot dev | Date: | Fri, 19 Jul 2019 00:13:21 +0000 |
| Subject: | note 124049 added to function.pcntl-signal | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-211618@lists.php.net to get a copy of this message | ||
Remember that signal handlers are called immediately, so every time when your process receives
registered signal blocking functions like sleep() and usleep() are interrupted (or more like ended)
like it was their time to finish.
This is expected behaviour, but not mentioned in this documentation. Sleep interruption can be very
unfortunate when for example you run a daemon that is supposed to execute some important task
exactly every X seconds/minutes - this task could be called too early or too often and it would be
hard to debug why it's happening exactly.
Simply remember that signal handlers might interfere with other parts of your code.
Here is example workaround ensuring that function gets executed every minute no matter how many
times our loop gets interrupted by incoming signal (SIGUSR1 in this case).
<?php
pcntl_async_signals(TRUE);
pcntl_signal(SIGUSR1, function($signal) {
// do something when signal is called
});
function everyMinute() {
// do some important stuff
}
$wait = 60;
$next = 0;
while (TRUE) {
$stamp = time();
do {
if ($stamp >= $next) { break; }
$diff = $next - $stamp;
sleep($diff);
$stamp = time();
} while ($stamp < $next);
everyMinute();
$next = $stamp + $wait;
sleep($wait);
}
?>
So in this infinite loop do {} while() calculates and adds missing sleep() to ensure that our
everyMinute() function is not called too early. Both sleep() functions here are covered so
everyMinute() will never be executed before it's time even if process receives multiple SIGUSR1
signals during it's runtime.
----
Server IP: 208.43.231.9
Probable Submitter: 185.85.3.195 (proxied: 2a05:dfc7:46:babb:6e7::)
----
Manual Page -- http://php.net/manual/en/function.pcntl-signal.php
Edit -- https://master.php.net/note/edit/124049
Del: integrated -- https://master.php.net/note/delete/124049/integrated
Del: useless -- https://master.php.net/note/delete/124049/useless
Del: bad code -- https://master.php.net/note/delete/124049/bad+code
Del: spam -- https://master.php.net/note/delete/124049/spam
Del: non-english -- https://master.php.net/note/delete/124049/non-english
Del: in docs -- https://master.php.net/note/delete/124049/in+docs
Del: other reasons-- https://master.php.net/note/delete/124049
Reject -- https://master.php.net/note/reject/124049
Search -- https://master.php.net/manage/user-notes.php