+ timespec now;
+ clock_gettime(CLOCK_MONOTONIC, &now);
+
+ if (timespec_less_than(now, next_frame)) {
+ // Wait until the next frame.
+ if (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME,
+ &next_frame, nullptr) == -1) {
+ if (errno == EINTR) continue; // Re-check the flag and then sleep again.
+ perror("clock_nanosleep");
+ exit(1);
+ }
+ } else {
+ // We've seemingly missed a frame. If we're more than one second behind,
+ // reset the timer; otherwise, just keep going.
+ timespec limit = next_frame;
+ ++limit.tv_sec;
+ if (!timespec_less_than(now, limit)) {
+ fprintf(stderr, "More than one second of missed fake frames; resetting clock.\n");
+ next_frame = now;
+ }
+ }