skalibs

Mirror/fork of https://skarnet.org/software/skalibs/
git clone https://ccx.te2000.cz/git/skalibs
Log | Files | Refs | README | LICENSE

alarm_milliseconds.c (1389B)


      1 /* ISC license. */
      2 
      3 #include <skalibs/sysdeps.h>
      4 #include <skalibs/alarm.h>
      5 
      6 #ifdef SKALIBS_HASTIMER
      7 
      8 #include <errno.h>
      9 #include <signal.h>
     10 #include <time.h>
     11 #include "alarm-internal.h"
     12 
     13 #undef MYCLOCK
     14 #ifdef SKALIBS_HASCLOCKMON
     15 # define MYCLOCK CLOCK_MONOTONIC
     16 #else
     17 # define MYCLOCK CLOCK_REALTIME
     18 #endif
     19 
     20 int alarm_milliseconds (unsigned int t)
     21 {
     22   struct itimerspec it = { .it_interval = { .tv_sec = 0, .tv_nsec = 0 }, .it_value = { .tv_sec = t / 1000, .tv_nsec = 1000000 * (t % 1000) } } ;
     23   struct sigevent se = { .sigev_notify = SIGEV_SIGNAL, .sigev_signo = SIGALRM, .sigev_value = { .sival_int = 0 }, .sigev_notify_function = 0, .sigev_notify_attributes = 0 } ;
     24   if (timer_create(MYCLOCK, &se, &timer_here) < 0) return 0 ;
     25   if (timer_settime(timer_here, 0, &it, 0) < 0)
     26   {
     27     int e = errno ;
     28     timer_delete(timer_here) ;
     29     errno = e ;
     30     return 0 ;
     31   }
     32   return 1 ;
     33 }
     34 
     35 #else
     36 #ifdef SKALIBS_HASITIMER
     37 
     38 #include <sys/time.h>
     39 
     40 int alarm_milliseconds (unsigned int t)
     41 {
     42   struct itimerval it = { .it_interval = { .tv_sec = 0, .tv_usec = 0 }, .it_value = { .tv_sec = t / 1000, .tv_usec = 1000 * (t % 1000) } } ;
     43   if (setitimer(ITIMER_REAL, &it, 0) < 0) return 0 ;
     44   return 1 ;
     45 }
     46 
     47 #else
     48 
     49 #include <unistd.h>
     50 #include <limits.h>
     51 
     52 int alarm_milliseconds (unsigned int t)
     53 {
     54   if (t > UINT_MAX - 999) return 0 ;
     55   t = (t + 999) / 1000 ;
     56   alarm(t) ;
     57   return 1 ;
     58 }
     59 
     60 #endif
     61 #endif