My program is supposed to print a number every second from 0 to 10 and never higher than 10. I put that in my main loop with While(1) to do it forever.
I have a SIGINT handler to increment the number 1 or -1 for SIGINT and SIGTERM respectively.
I am trying to implement a second handler to capture a second SIGINT signal within one second of the first to quit the program, but my second handler (sig_handler_2) is never reached. What am I doing wrong?
Source Code:
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
int number = 0;
void sig_handler_2(int sig) {
printf("Exiting the program now \n");
signal(SIGINT, SIG_DFL);
}
void sig_handler_1(int sig) {
signal(SIGINT, sig_handler_2);
if (sig == SIGINT) {
if (number > 9) {
printf(" SIGINT received but number is > 9, cannot increment \n");
}
else {
printf(" SIGINT received: Increment is now %d \n", number);
}
}
if (sig == SIGTERM) {
if (number <= 0) {
printf(" SIGTERM received but number <= 0, cannot increment \n");
}
else {
number --;
printf(" SIGTERM received: Increment is now %d \n", number);
printf("%d \n", number);
}
}
}
int main() {
while (1) {
signal(SIGINT, sig_handler_1);
signal(SIGTERM, sig_handler_1);
if (number > 9) {
printf("%d \n", number);
number = 0;
}
else {
printf("%d \n", number);
number ++;
}
sleep(1);
}
}`