1
0

ticker_demo.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /* ticker_demo.c
  2. * demonstrates use of interval timer to generate reqular
  3. * signals, which are in turn caught and used to count down
  4. */
  5. #include <stdio.h>
  6. #include <sys/time.h>
  7. #include <signal.h>
  8. int main()
  9. {
  10. void countdown(int);
  11. signal(SIGALRM, countdown);
  12. if ( set_ticker(500) == -1 )
  13. perror("set_ticker");
  14. else
  15. while( 1 )
  16. pause();
  17. return 0;
  18. }
  19. void countdown(int signum)
  20. {
  21. static int num = 10;
  22. printf("%d ..", num--);
  23. fflush(stdout);
  24. if ( num < 0 ){
  25. printf("DONE!\n");
  26. exit(0);
  27. }
  28. }
  29. /* [from set_ticker.c]
  30. * set_ticker( number_of_milliseconds )
  31. * arranges for interval timer to issue SIGALRM's at regular intervals
  32. * returns -1 on error, 0 for ok
  33. * arg in milliseconds, converted into whole seconds and microseconds
  34. * note: set_ticker(0) turns off ticker
  35. */
  36. int set_ticker( int n_msecs )
  37. {
  38. struct itimerval new_timeset;
  39. long n_sec, n_usecs;
  40. n_sec = n_msecs / 1000 ; /* int part */
  41. n_usecs = ( n_msecs % 1000 ) * 1000L ; /* remainder */
  42. new_timeset.it_interval.tv_sec = n_sec; /* set reload */
  43. new_timeset.it_interval.tv_usec = n_usecs; /* new ticker value */
  44. new_timeset.it_value.tv_sec = n_sec ; /* store this */
  45. new_timeset.it_value.tv_usec = n_usecs ; /* and this */
  46. return setitimer(ITIMER_REAL, &new_timeset, NULL);
  47. }