Simple Signals - C programming and alarm function

后端 未结 4 1584
挽巷
挽巷 2020-12-01 04:39
#include  
#include  


void  ALARMhandler(int sig)
{
  signal(SIGALRM, SIG_IGN);          /* ignore this signal       */
  printf(\"H         


        
4条回答
  •  孤城傲影
    2020-12-01 05:12

    You're not setting the handler in your main function.

    Before you do alarm(2), put the signal(SIGALRM, ALARMhandler); in your main.

    It should work then.

    Note that your "All Done" will never be printed, because you'll stay in the while(1) loop after the signal processor has run. If you want the loop to be broken, you'll need to have a flag that the signal handler changes.

    #include 
    #include 
    #include 
    
    /* number of times the handle will run: */
    volatile int breakflag = 3;
    
    void handle(int sig) {
        printf("Hello\n");
        --breakflag;
        alarm(1);
    }
    
    int main() {
        signal(SIGALRM, handle);
        alarm(1);
        while(breakflag) { sleep(1); }
        printf("done\n");
        return 0;
    }
    

提交回复
热议问题