timer_create.c 1.8 KB

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