Samuel Magaña
Samuel Magaña

Reputation: 27

Sigaction and SIGALRM

Hi I'm trying to learn more about signals and I wrote a simple code that supposed to just print "bye" everything the alarm signal is send. I am using sigaction to set this. However, I keep returning NULL in my error checking could someone tell me what I'm doing wrong. Thanks in Advance!

    #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");
    }

Upvotes: 0

Views: 2605

Answers (1)

hdante
hdante

Reputation: 8020

sigaction cannot return null, since it returns an integer. I'm assuming it's returning -1. You're not correctly initializing the sigaction structure. It has many fields, but you're allowing them to be undefined. Fix the structure definition and try again. See:

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

Upvotes: 1

Related Questions