timer_create.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * timer_create.c - create a per-process timer.
  3. */
  4. #include <errno.h>
  5. #include <signal.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <time.h>
  9. #include <sys/syscall.h>
  10. #include "kernel-posix-timers.h"
  11. #ifdef __NR_timer_create
  12. #ifndef offsetof
  13. # define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
  14. #endif
  15. #define __NR___syscall_timer_create __NR_timer_create
  16. static inline _syscall3(int, __syscall_timer_create, clockid_t, clock_id,
  17. struct sigevent *, evp, kernel_timer_t *, ktimerid);
  18. /* Create a per-process timer */
  19. int timer_create(clockid_t clock_id, struct sigevent *evp, timer_t * timerid)
  20. {
  21. int retval;
  22. kernel_timer_t ktimerid;
  23. struct sigevent local_evp;
  24. struct timer *newp;
  25. /* Notification via a thread is not supported yet */
  26. if (__builtin_expect(evp->sigev_notify == SIGEV_THREAD, 1))
  27. return -1;
  28. /*
  29. * We avoid allocating too much memory by basically using
  30. * struct timer as a derived class with the first two elements
  31. * being in the superclass. We only need these two elements here.
  32. */
  33. newp = (struct timer *)malloc(offsetof(struct timer, thrfunc));
  34. if (newp == NULL)
  35. return -1; /* No memory */
  36. if (evp == NULL) {
  37. /*
  38. * The kernel has to pass up the timer ID which is a userlevel object.
  39. * Therefore we cannot leave it up to the kernel to determine it.
  40. */
  41. local_evp.sigev_notify = SIGEV_SIGNAL;
  42. local_evp.sigev_signo = SIGALRM;
  43. local_evp.sigev_value.sival_ptr = newp;
  44. evp = &local_evp;
  45. }
  46. retval = __syscall_timer_create(clock_id, evp, &ktimerid);
  47. if (retval != -1) {
  48. newp->sigev_notify = (evp != NULL ? evp->sigev_notify : SIGEV_SIGNAL);
  49. newp->ktimerid = ktimerid;
  50. *timerid = (timer_t) newp;
  51. } else {
  52. /* Cannot allocate the timer, fail */
  53. free(newp);
  54. retval = -1;
  55. }
  56. return retval;
  57. }
  58. #endif