skalibs

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

alarm_timeout.c (1441B)


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