I am working on the following code. The program should be able to handle SIGINT with sigaction. So far, it's almost done, but I have come along two problems.
The first problem is the program should print "Shutting down" and exit with status 1 if it receives 3 signals within 3 seconds.
The second problem is I am using gettimeofday and struct timeval to get the time in seconds regarding to the arrival times of the signals, but I failed here as well. When I tried it out, I got stuck in an infinite loop, even thought I pressed ctrl + C 3 times within 3 seconds. Also, the resulting seconds are quite big numbers.
I hope someone could help me to get these two problems done. Here's the code
int timeBegin = 0;
void sig_handler(int signo) {
(void) signo;
struct timeval t;
gettimeofday(&t, NULL);
int timeEnd = t.tv_sec + t.tv_usec;
printf("Received Signal\n");
int result = timeEnd - timeBegin;
if(check if under 3 seconds) { // How to deal with these two problems?
printf("Shutting down\n");
exit(1);
}
timeBegin = timeEnd // EDIT: setting the time new, each time when a signal arrives. Is that somehow helpful?
}
int main() {
struct sigaction act;
act.sa_handler = &sig_handler;
sigaction(SIGINT, &act, NULL);
for( ;; ) {
sleep(1);
}
return 0;
}
That won't work because
tv_sec
andtv_usec
are different orders of magnitude. If you want microsecond accuracy, you'll have to store the value in a larger type (e.g.int64_t
) and convert the seconds to microseconds.Well, what have you tried? You have several signals arriving at different times, you need to keep some state about them to know if all arrived within 3 seconds of each other.