Just learned about sigacation, also implemented another timer to make it more interesting.
#include
#include
#include
A (pedantically) correct signal handler can do very few things: notably setting a volatile sig_atomic_t
variable (this is some integer type), and perhaps calling siglongjmp
[I'm not even sure for siglongjmp
].
So declare first
volatile sig_atomic_t gotsignal;
then your signal handler is simply
void handler (void)
{
gotsignal = 1;
}
and your loop is
while(!gotsignal && x < y){
printf("Insert a value: \n");
scanf("%d", &value);
x+=value;
}
Don't forget that asynchronous signals happen at any time (any machine instruction!!!), including inside malloc
or printf
. 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.