timer_create.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 default_evp;
  24. struct timer *newp;
  25. if (evp == NULL) {
  26. /*
  27. * The kernel has to pass up the timer ID which is a userlevel object.
  28. * Therefore we cannot leave it up to the kernel to determine it.
  29. */
  30. default_evp.sigev_notify = SIGEV_SIGNAL;
  31. default_evp.sigev_signo = SIGALRM;
  32. evp = &default_evp;
  33. }
  34. /* Notification via a thread is not supported yet */
  35. if (__builtin_expect(evp->sigev_notify == SIGEV_THREAD, 1))
  36. return -1;
  37. /*
  38. * We avoid allocating too much memory by basically using
  39. * struct timer as a derived class with the first two elements
  40. * being in the superclass. We only need these two elements here.
  41. */
  42. newp = malloc(offsetof(struct timer, thrfunc));
  43. if (newp == NULL)
  44. return -1; /* No memory */
  45. default_evp.sigev_value.sival_ptr = newp;
  46. retval = __syscall_timer_create(clock_id, evp, &ktimerid);
  47. if (retval != -1) {
  48. newp->sigev_notify = evp->sigev_notify;
  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