Skip to content

Instantly share code, notes, and snippets.

@Grissess
Created August 24, 2024 01:37
Show Gist options
  • Save Grissess/e866e9807da0d8a98d17b4b2daf71302 to your computer and use it in GitHub Desktop.
Save Grissess/e866e9807da0d8a98d17b4b2daf71302 to your computer and use it in GitHub Desktop.
A little program that shows the time, ticking on the second, as exactly as the OS allows
/* cc -o thetime thetime.c -lrt */
#include <signal.h>
#include <time.h>
#include <stdio.h>
#define BUFSZ 128
int main() {
timer_t timer;
struct itimerspec itspec;
sigset_t sigset;
int signo;
struct timespec now;
struct tm now_tm;
char buf[BUFSZ];
int phase = 0;
if(sigemptyset(&sigset)) {
perror("sigemptyset");
return 1;
}
if(sigaddset(&sigset, SIGALRM)) {
perror("sigaddset");
return 1;
}
if(sigprocmask(SIG_BLOCK, &sigset, NULL)) {
perror("sigprocmask");
return 1;
}
if(timer_create(CLOCK_REALTIME, NULL, &timer)) {
perror("timer_create");
return 1;
}
if(clock_gettime(CLOCK_REALTIME, &itspec.it_value)) {
perror("clock_gettime");
return 1;
}
itspec.it_interval.tv_sec = 1;
itspec.it_interval.tv_nsec = 0;
itspec.it_value.tv_sec++;
itspec.it_value.tv_nsec = 0;
if(timer_settime(timer, TIMER_ABSTIME, &itspec, NULL)) {
perror("timer_settime");
return 1;
}
while(1) {
if(sigwait(&sigset, &signo)) {
perror("sigwait");
return 1;
}
if(signo != SIGALRM) continue;
if(clock_gettime(CLOCK_REALTIME, &now)) {
perror("clock_gettime");
return 1;
}
localtime_r(&now.tv_sec, &now_tm);
if(!strftime(buf, BUFSZ, "%FT%T", &now_tm)) {
perror("strftime");
return 1;
}
if(printf("\r\x1b[K%s.%09ld %s", buf, now.tv_nsec, phase ? "TICK" : "TOCK") < 0) {
perror("printf");
return 1;
}
if(fflush(stdout)) {
perror("fflush");
return 1;
}
phase = !phase;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment