Reputation: 141
I'm starting to learn signals and how to trigger them. I have this simple code that triggers a signal using SIGUSR1, but when I run the code, the only thing that gets printed is the "Starting..." line. Nothing else gets printed. Am I doing something wrong?
#include <signal.h>
#include <stdio.h>
void my_handler(int signum)
{
printf("Hello\n");
printf("%d\n", signum);
if (signum == SIGUSR1) {
printf("Receveid\n");
}
}
int main() {
printf("Starting...\n");
signal(SIGUSR1, my_handler);
return 0;
}
Upvotes: 0
Views: 1007
Reputation: 26375
signal
only registers a signal handler - the function to be called when the process receives a signal. From within your program, you can use raise
to send a signal to the calling process.
If you are in a POSIX environment, you should take a look at man 7 signal-safety
for a list of functions that are safe to call from within signal handlers (additional information in this answer). printf
is not included in this list - nor are a lot standard library functions. Its better to use an operation which is atomic with regards to signals, such as write
(or reentrant, such as strlen
).
A cursory example of using raise
, which returns 0
on success, and nonzero on error.
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
void my_handler(int signum) {
char msg[] = "SIGUSR1 handler\n";
if (signum == SIGUSR1)
write(STDOUT_FILENO, msg, strlen(msg));
}
int main(void) {
printf("Starting...\n");
signal(SIGUSR1, my_handler);
(void) getchar();
if (raise(SIGUSR1) != 0)
fprintf(stderr, "Could not raise signal.\n");
}
Upvotes: 2