You need to be careful what you do in a signal handler. It's best that they do as little as possible. In particular, functions like printf are generally not supposed to be used inside them. signal-safety(7) - Linux manual page
Instead of defining your own True, just use <stdbool.h> which defines true, false, and bool.
You'll need to kill the program from another terminal:
Code:
$ ps -C a.out
PID TTY TIME CMD
10374 pts/0 00:00:00 a.out
$ kill -s USR1 10374
Keys:
SIGINT: ctrl+C
SIGQUIT: ctrl+\ (or maybe ctrl+Y)
Code:
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#define NumMessages 2
sig_atomic_t g_msg_num = -1;
sig_atomic_t g_cur_msg_num = 0;
void work() {
static const char *msgs[] = {
"message 1",
"message 2"
};
while (true) {
sleep(1); // one second is enough
if (g_msg_num != -1) {
printf("%s\n", msgs[g_msg_num]);
g_msg_num = -1;
}
}
}
void inthdlr(int n) {
g_msg_num = g_cur_msg_num;
signal(SIGINT, inthdlr);
}
void quithdlr(int n) {
g_cur_msg_num = (g_cur_msg_num + 1) % NumMessages;
signal(SIGQUIT, quithdlr);
}
int main() {
signal(SIGINT, inthdlr);
signal(SIGQUIT, quithdlr);
work();
}