2
#include <iostream>
#include <signal.h>
#include <unistd.h>

using namespace std;

void sighandler(int sig) {
    cout << "signal received" << endl;
}

int main() {

    int pid= getpid();
    cout << pid << endl;

    signal( SIGUSR1, sighandler );

    sigset_t accept;
    sigaddset( &accept, SIGUSR1 );
    int s;

    sigwait(&accept, &s);

    cout << s << endl;

    return 0;
}

When I run this program and send a SIGUSR1 signal to it via "kill -s SIGUSR1 $pid" it just outputs the number of the signal (10) but not the text in sighandler. I don't understand why. This is on a Linux System.

Deanie
  • 2,316
  • 2
  • 19
  • 35
blues
  • 4,547
  • 3
  • 23
  • 39
  • 3
    You might want to add `sigemptyset(&accept)` prior to your `sigaddset`. – John Ledbetter Mar 05 '13 at 20:25
  • 3
    using `cout` in a signal handler invokes [undefined behavior](http://stackoverflow.com/questions/2013202/i-need-a-list-of-async-signal-safe-functions-from-glibc). Don't do that, write a signal handler [correctly](http://lazarenko.me/2013/01/15/how-not-to-write-a-signal-handler/). – Sam Miller Mar 05 '13 at 20:28

3 Answers3

6

From sigwait - wait for queued signals

DESCRIPTION

The sigwait() function selects a pending signal from set, atomically clears it from the system's set of pending signals, and returns that signal number in the location referenced by sig.

So, by using sigwait(), the signal is already delivered and dealt with by your program.

When you remove the sigwait call and do a sleep or busy waiting, the SIGUSR1 signal will be delivered to your signal handler and the message "signal received" will be printed.

Community
  • 1
  • 1
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
3

You're getting this behavior because when you call sigwait() your thread gets put to sleep and control gets passed to the OS. When you send the SIGUSR1 signal, it is getting handled by the OS, and then the OS wakes up your thread and passes control back. Even though you've registered a signal handler, your handler is not getting called because the signal has been handled by the time your thread is re-awakened.

ryanbwork
  • 2,123
  • 12
  • 12
1

I am trying to find a definitive reference, but it appears that the signal handler and sigwait are mutually exclusive. If you handle the signal synchronously, using sigwait, the handler is never invoked.

For a discussion, see About the ambiguous description of sigwait()

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012