Pcntl_sigwaitinfo and signal handlers

I write a demon that periodically does some work and sleeps for a while before repeating it again. But he still has to respond to external influences (i.e. Request for completion) during sleep.

I managed to implement a wait timeout with an ALRM signal and termination with a TERM signal (sample):

// ... declare(ticks = 1); function do_work() { echo "Doing some work.\n"; } $term = FALSE; $sighandler = function ($signal) use (&$term) { if ($signal === SIGTERM) { pcntl_alarm(0); $term = TRUE; echo "TERM HANDLER\n"; } else { echo "ALRM HANDLER\n"; } }; pcntl_signal(SIGALRM, $sighandler); pcntl_signal(SIGTERM, $sighandler); while (!$term) { do_work(); // Kick myself after 2 seconds pcntl_alarm(2); // Wait for alarm or termination $signal = pcntl_sigwaitinfo(array(SIGTERM, SIGALRM), $info); pcntl_signal_dispatch(); switch ($signal) { case SIGALRM: echo "ALRM SIGWI\n"; break; case SIGTERM: echo "TERM SIGWI\n"; $term = TRUE; break; } } // ... 

But for God's sake I can’t understand why the sighandler is never called. I get the following output:

 $ php sigsample.php Doing some work. ALRM SIGWI Doing some work. ALRM SIGWI Doing some work. TERM SIGWI 

And at the same time, if I do not install this handler, the script dies due to an unprocessed signal.

Am I missing something? Why has my signal handler function never been called? Does pcntl_sigwaitinfo () work?

And are there any other means for using timeout and signal processing at the same time?

+4
source share
1 answer

This is not entirely unexpected.

You requested delivery to the signal handler ( pcntl_signal(...) ), but then asked to receive the signal without calling any handlers ( pcntl_sigwaitinfo(...) ). Your OS will decide what happens in this case, and your OS (like mine) will decide to let pcntl_sigwaitinfo() win.

Background

A process can receive ("suffer?") A signal in two different ways:

  • asynchronous delivery

    The signal triggers some asynchronous action, usually killing the process or invoking a user-defined handler. pcntl_signal only registers such a handler.

    Key calls familiar to C, signal and sigaction .

  • synchronous adoption

    Special system functions note that the signal is waiting, and remove it from the waiting list, returning information about the signal to the process. pcntl_sigwaitinfo is such a function.

    The main calls are sigwait , sigwaitinfo and sigtimedwait .

The two delivery and acceptance methods are different and are not intended to be shared . AIX, for example, simply prohibits "[c] from using the current use of sigaction and sigwait . "

(In connection with the foregoing, we understand a signal mask that can “block” signals, effectively making them remain pending until they are received or until they are “unlocked” and delivered.)

+3
source

Source: https://habr.com/ru/post/1438992/


All Articles