need programs that illustrate use of settimer and alarm functions in GNU C

前端 未结 1 1671
一整个雨季
一整个雨季 2020-12-18 11:17

Can anyone illustrate the use of settimer or alarm function in gnu C , with some program examples ,please ?

I have a program that continuously proce

相关标签:
1条回答
  • 2020-12-18 11:41

    Here's an example from here which uses setitimer() to periodically call DoStuff().

    The key here is that calling setitimer() results in the OS scheduling a SIGALRM to be sent to your process after the specified time has elapsed, and it is up to your program to handle that signal when it comes. You handle the signal by registering a signal handler function for the signal type (DoStufF() in this case) after which the OS will know to call that function when the timer expires.

    You can read the setitimer() man page to figure out what the arguments are and how to cancel a timer.

    Note: if you want the timer to trigger only once, you will have to call alarm() or ualarm() instead of setitimer().

    /*
     * setitimer.c - simple use of the interval timer
     */
    
    #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(void);
    
    int main(int argc, char *argv[]) {
    
      struct itimerval it_val;  /* for setting itimer */
    
      /* Upon SIGALRM, call DoStuff().
       * Set interval timer.  We want frequency in ms, 
       * but the setitimer call needs seconds and useconds. */
      if (signal(SIGALRM, (void (*)(int)) DoStuff) == SIG_ERR) {
        perror("Unable to catch SIGALRM");
        exit(1);
      }
      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) {
        perror("error calling setitimer()");
        exit(1);
      }
    
      while (1) 
        pause();
    
    }
    
    /*
     * DoStuff
     */
    void DoStuff(void) {
    
      printf("Timer went off.\n");
    
    }
    
    0 讨论(0)
提交回复
热议问题