Just learned about sigacation, also implemented another timer to make it more interesting.
#include <stdio.h>
#include <signal.h>
#include <sys/time.h>
volatile sig_atomic_t gotsignal;
void handler(){
gotsignal = 1;
}
int main(){
struct sigaction sig;
struct itimerval timer;
timer.it_value.tv_sec = 5;
timer.it_value.tv_usec = 0;
timer.it_interval = timer.it_value;
sig.sa_handler = handler;
sig.sa_flags = 0;
sigemptyset(&sig.sa_mask);
setitimer(ITIMER_REAL, &timer, 0);
sigaction(SIGALRM, &sig, NULL);
int value, y = 100, x=0;
while(!gotsignal && x < y){
printf("Insert a value: \n");
scanf("%d", &value);
x+=value;
printf("Current x value: %d\n", x);
}
}
What i don’t understand is, when it is waiting for user input and i write 5, but not press enter. He still reads it? Shouldn’t he clear it off?
The output it gave me:
Insert a value:
1
Current x value: 1
Insert a value:
2
Current x value: 3
Insert a value:
5Current x value: 5
What I would want would be like:
Insert a value:
1
Current x value: 1
Insert a value:
2
Current x value: 3
Insert a value:
5(Wthout pressing enter!)Current x value: 3 (He would forget about 5 no?)
A (pedantically) correct signal handler can do very few things: notably setting a
volatile sig_atomic_tvariable (this is some integer type), and perhaps callingsiglongjmp[I’m not even sure forsiglongjmp].So declare first
then your signal handler is simply
and your loop is
Don’t forget that asynchronous signals happen at any time (any machine instruction!!!), including inside
mallocorprintf. Never call these functions from inside a handler.Bugs related to bad signal handling are hard to debug: they are not reproducible!
Consider perhaps using sigaction.