2017-05-24 48 views
0

嗨我想了解更多關於信號,我寫了一個簡單的代碼,應該只是打印「再見」所有的警報信號發送。我正在使用sigaction來設置它。然而,我一直在我的錯誤檢查中返回NULL,有人可以告訴我我做錯了什麼。提前致謝!Sigaction和SIGALRM

#include <stdio.h> 
    #include <stdlib.h> 
    #include <sys/wait.h> 
    #include <sys/time.h>  /* for setitimer */ 
    #include <unistd.h>  /* for pause */ 
    #include <signal.h>  /* for signal */ 
    #define INTERVAL 500  /* number of milliseconds to go off */ 

    /* function prototype */ 
    void DoStuff(); 

    int main(int argc, char *argv[]) { 
     struct itimerval it_val; /* for setting itimer */ 
     struct sigaction sa; 
     sa.sa_handler = &DoStuff; 

     /* Upon SIGALRM, call DoStuff(). 
     * Set interval timer. We want frequency in ms, 
     * but the setitimer call needs seconds and useconds. */ 
     if (sigaction(SIGALRM,&sa,NULL) < 0) { /*set the signal to be enabled if this action occurs*/ 
     perror("Unable to catch SIGALRM"); 
     exit(1); 
     } 

     it_val.it_interval = it_val.it_value; 
     it_val.it_value.tv_sec =  INTERVAL/1000; 
     it_val.it_value.tv_usec = (INTERVAL*1000) % 1000000; 
     it_val.it_interval = it_val.it_value; 
     if (setitimer(ITIMER_REAL, &it_val, NULL) == -1) { /*set the timer to send the alarm command*/ 
     perror("error calling setitimer()"); 
     exit(1); 
     } 
    while(1) 
    { 
      pause(); 
    } 


    } 

    void DoStuff() { 
     printf("bye\n"); 
    } 
+1

printf()不是信號處理程序安全的。 – ThingyWotsit

+0

發佈的代碼適合我。你看到什麼錯誤? –

+0

sigaction總是返回NULL –

回答