Real-time aware sleep() call?
A few solutions and potential solutions:
Sleep in a loop and check the real elapsed time
There is almost certainly a better way to do it—or there should be!—but here's an acceptable solution for my application for the time being:
When needing to sleep for a long interval (>30s), I do
sleep(30)
repeatedly, checking that the real elapsed time (time(NULL)-start_time
) is not longer than the total desired pause.This way, if the system is suspended for, say, 3 hours, while the desired program pause is 1 hour, the extra delay caused by the suspend will not exceed 30 seconds.
Code to do it:
void nullhandler(int signal) {}int isleep(int seconds, int verbose){ if (verbose) { fprintf(stderr, "Sleeping for %d seconds...", seconds); fflush(stderr); } signal(SIGALRM, nullhandler); // weird workaround for non-realtime-awareness of sleep: // https://stackoverflow.com/questions/32152276/real-time-aware-sleep-call int res=0, elapsed=0; for (time_t t=time(NULL); (elapsed<seconds) && (res<=0); elapsed=time(NULL)-t) res = sleep((seconds-elapsed > 30) ? 30 : seconds-elapsed); signal(SIGALRM, SIG_IGN); if (res && verbose) fprintf(stderr, "%s\n\n", res ? " woken by signal!" : ""); return (res>0);}
Wakeup callback
@Speed8ump suggested registering a callback for system-wakeup notifications. This thread over at AskUbuntu shows how to do it. A good solution, but I'd like to avoid tying my relatively-low-level code too strongly to a particular desktop environment for now.
timer_settime
This is the most elegant and correct solution, in my opinion, and was suggested by @NominalAnimal. It uses timer_settime()
and friends from librt
.
Note that in order to make this work correctly with system suspend, you must use CLOCK_REALTIME
with TIMER_ABSTIME
, per the timer_settime
documentation:
If the value of the CLOCK_REALTIME clock is adjusted while an absolutetimer based on that clock is armed, then the expiration of the timerwill be appropriately adjusted. Adjustments to the CLOCK_REALTIMEclock have no effect on relative timers based on that clock.
Here's a demo (link with librt
, e.g. gcc -lrt -o sleep sleep.c
):
#include <time.h>#include <stdio.h>#include <unistd.h>#include <signal.h>#include <sys/time.h>#include <string.h>#include <stdlib.h>void sighandler(int signal) {}void isleep(int seconds){ timer_t timerid; struct sigevent sev = { .sigev_notify=SIGEV_SIGNAL, .sigev_signo=SIGALRM, .sigev_value=(union sigval){ .sival_ptr = &timerid } }; signal(SIGALRM, sighandler); timer_create(CLOCK_REALTIME, &sev, &timerid); struct itimerspec its = {.it_interval={0,0}}; clock_gettime(CLOCK_REALTIME, &its.it_value); its.it_value.tv_sec += seconds; timer_settime(timerid, TIMER_ABSTIME, &its, NULL); pause(); signal(SIGALRM, SIG_IGN);}int main(int argc, char**argv){ time_t t=time(NULL); printf("sleep at: %s", ctime(&t)); isleep(atoi(argv[1])); t=time(NULL); printf("wake at: %s", ctime(&t));}