timer.c 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include <signal.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include "include/log.h"
  5. #include "include/list.h"
  6. #include "include/timer.h"
  7. #include "include/ucix.h"
  8. /* when using this file, alarm() is used */
  9. static struct list_head timers;
  10. struct timer {
  11. struct list_head list;
  12. int count;
  13. int timeout;
  14. timercb_t timercb;
  15. };
  16. void timer_add(timercb_t timercb, int timeout)
  17. {
  18. struct timer *timer;
  19. timer = malloc(sizeof(struct timer));
  20. if(!timer)
  21. {
  22. log_printf("unable to get timer buffer\n");
  23. return;
  24. }
  25. timer->count = 0;
  26. timer->timeout = timeout;
  27. timer->timercb = timercb;
  28. INIT_LIST_HEAD(&timer->list);
  29. list_add(&timer->list, &timers);
  30. }
  31. static void timer_proc(int signo)
  32. {
  33. struct list_head *p;
  34. list_for_each(p, &timers)
  35. {
  36. struct timer *q = container_of(p, struct timer, list);
  37. q->count++;
  38. if(!(q->count%q->timeout))
  39. {
  40. q->timercb();
  41. }
  42. }
  43. alarm(1);
  44. }
  45. void timer_init(void)
  46. {
  47. struct sigaction s;
  48. INIT_LIST_HEAD(&timers);
  49. s.sa_handler = timer_proc;
  50. s.sa_flags = 0;
  51. sigaction(SIGALRM, &s, NULL);
  52. alarm(1);
  53. }