I'm brand new to c programming and am struggling with an assignment. The basics of the code is to have a 1 second timer (I'm using sleep(1)) that counts up starting with an increment of 1. Every time I send sigINT, I increase the increment by 1 and the counter prints off the new number. I use sigterm to decrement the number. All of this is working fine.
The last part is to kill the program if I use sigINT twice in one second. I have tried doing this with a "flag" which for me is set to 0. When the sigINT is called, increase it by 1. Have it reset to 0 in my while loop. I tried writing an if statement that if the increment is more than 1, the program would stop. But with sleep(0) and flag=0 right after that, I can never get the flag to be more than 1. I know this probably isn't the best way to do this, but have had no luck in finding a better solution. Any help is appreciated. Thanks.
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
int inc = 1;
int flag = 0;
void handle_sigint(int sig_num)
{
signal(SIGINT, handle_sigint);
if (inc < 10)
{
inc++;
}
flag++;
printf("\nflag=%d\n", flag);
printf("\nSIGINT received: Increment is now %d\n", inc);
fflush(stdout);
}
void handle_sigterm(int sig_num)
{
signal(SIGTERM, handle_sigterm);
if (inc > 0)
{
inc--;
}
printf("\nSIGTERM received: Increment is now %d\n", inc);
fflush(stdout);
}
int main()
{
int num = 0;
signal(SIGINT, handle_sigint);
signal(SIGTERM, handle_sigterm);
printf("Process ID: %d\n", getpid());
while (1)
{
if (flag > 1)
{
pid_t iPid = getpid();
printf("\nExiting the program now\n");
kill(iPid, SIGKILL);
}
printf("%d\n", num);
num = num + inc;
sleep(1);
flag = 0;
}
return 0;
}