I’m trying to understand the following example code about signals:
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
sig_atomic_t sigusr1_count = 0;
void handler(int signal_number) {
++sigusr1_count;
}
int main() {
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = &handler;
sigaction(SIGUSR1, &sa, NULL );
printf("SIGUSR1 was raised %d times\n", sigusr1_count);
return 0;
}
The output is:
SIGUSR1 was raised 0 times
Why was the signal not raised?
There are a couple of reasons. The first, is that nothing ever sends SIGUSR1 to your process. The other, more important one, is that you don’t give any time for anyone to do so. Immediately after registering your signal handler, you print out how many times the signal was received in, most likely, less then a few milliseconds. You need to add something like
sleep(10)before printing out the result.