main.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <err.h>
  5. #include <sys/time.h>
  6. #include <signal.h>
  7. #include <sys/syscall.h>
  8. #include <sys/timerfd.h>
  9. static int do_print;
  10. static int do_quit;
  11. static size_t loops;
  12. void sig_handler(int signum)
  13. {
  14. printf("ok");
  15. switch (signum)
  16. {
  17. case SIGQUIT:
  18. case SIGTERM:
  19. case SIGINT:
  20. signal(SIGINT, SIG_DFL);
  21. do_quit = 1;
  22. __attribute__((fallthrough));
  23. case SIGUSR1:
  24. do_print = 1;
  25. break;
  26. case SIGHUP:
  27. loops = 0;
  28. default:
  29. break;
  30. }
  31. }
  32. int deadline(size_t period_ms)
  33. {
  34. #ifndef EDF
  35. int tfd = -1;
  36. struct itimerspec itval;
  37. int rc = 0;
  38. tfd = timerfd_create(CLOCK_MONOTONIC, 0);
  39. if (tfd == -1)
  40. err(-1, "timerfd");
  41. itval.it_interval.tv_sec = 0;
  42. itval.it_interval.tv_nsec = period_ms * 1000 * 1000;
  43. itval.it_value.tv_sec = 0;
  44. itval.it_value.tv_nsec = itval.it_interval.tv_nsec;
  45. rc = timerfd_settime(tfd, 0, &itval, NULL);
  46. if (rc)
  47. err(-1, "timerfd_settime");
  48. do {
  49. static unsigned long long overrun;
  50. rc = read(tfd, &overrun, sizeof overrun);
  51. if (rc == -1) {
  52. err(-1, "Timer read");
  53. }
  54. ++loops;
  55. if (do_print) {
  56. do_print = 0;
  57. fprintf(stdout, "Loops: %zu.\n", loops);
  58. }
  59. } while(!do_quit);
  60. #endif
  61. }
  62. int main(int argc, char *argv[])
  63. {
  64. int rc;
  65. struct sigaction sa = {0};
  66. /* Set up the structure to specify the new action. */
  67. sigemptyset (&sa.sa_mask);
  68. sigaddset(&sa.sa_mask, SIGINT);
  69. sa.sa_handler = &sig_handler;
  70. sa.sa_flags = 0;
  71. sigaddset(&sa.sa_mask, SIGTERM);
  72. sigaddset(&sa.sa_mask, SIGINT);
  73. sigaddset(&sa.sa_mask, SIGHUP);
  74. sigaddset(&sa.sa_mask, SIGUSR1);
  75. sigaddset(&sa.sa_mask, SIGQUIT);
  76. if (sigaction (SIGINT, &sa, NULL) == -1) {
  77. perror("sigaction");
  78. exit(EXIT_FAILURE);
  79. }
  80. sigaction (SIGTERM, &sa, NULL);
  81. sigaction (SIGQUIT, &sa, NULL);
  82. sigaction (SIGUSR1, &sa, NULL);
  83. sigaction (SIGHUP, &sa, NULL);
  84. printf("[%d] Starting deadline thread.\n", getpid());
  85. rc = deadline(500);
  86. exit(rc ? EXIT_FAILURE : EXIT_SUCCESS);
  87. }