scanf loop, and signal handler

萝らか妹 提交于 2019-12-02 18:22:52

问题


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?)

回答1:


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.



来源:https://stackoverflow.com/questions/8281763/scanf-loop-and-signal-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!