scanf loop, and signal handler

大憨熊 提交于 2019-12-02 08:37:51

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.

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