scanf loop, and signal handler

前端 未结 1 1050
迷失自我
迷失自我 2021-01-25 23:29

Just learned about sigacation, also implemented another timer to make it more interesting.

#include 
#include  
#include 

        
相关标签:
1条回答
  • 2021-01-25 23:58

    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.

    0 讨论(0)
提交回复
热议问题