Sigaction和SIGALRM

时间:2017-05-24 01:23:50

标签: c

您好我正在尝试了解有关信号的更多信息,并且我编写了一个简单的代码,该代码应该只打印报警信号发送的“再见”。我正在使用sigaction来设置它。但是,我在错误检查中一直返回NULL,有人可以告诉我我做错了什么。在此先感谢!

    #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 个答案:

答案 0 :(得分:1)

sigaction不能返回null,因为它返回一个整数。我假设它正在返回-1。您没有正确初始化sigaction结构。它有很多字段,但你允许它们未定义。修复结构定义,然后重试。参见:

http://man7.org/linux/man-pages/man2/sigaction.2.html