blues blues - 4 months ago 5
Linux Question

Why is signalhandler not outputting anything?

#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.


From sigwait - wait for queued signals


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.