Skip to content

Instantly share code, notes, and snippets.

@zouppen
Created May 15, 2014 08:44
Show Gist options
  • Select an option

  • Save zouppen/6a193c9a02e6d442eedf to your computer and use it in GitHub Desktop.

Select an option

Save zouppen/6a193c9a02e6d442eedf to your computer and use it in GitHub Desktop.
Console tick clock
/**
* Console tick clock by Joel Lehtonen, joel.lehtonen ät iki.fi
* Public Domain
*
* Clock which outputs a character every second. The time displayed
* matches the wall clock at every newline.
*
* This may experience leap second issue. Not tested with that. Also,
* sorry about the magic numbers. This is just a funny console clock,
* not a proof of work :-)
*/
#include <err.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/timerfd.h>
#include <time.h>
#include <unistd.h>
#define GUARD(x) { if ((x)==-1) err(1,"Unable to initialize clock"); }
void init_clock(int *fd, time_t *now);
void init_clock(int *fd, time_t *now)
{
struct timespec start;
struct itimerspec spec;
GUARD(clock_gettime(CLOCK_REALTIME, &start));
*now = start.tv_sec/20*20; // Multiple of date string length
/* Define a timer which starts exactly on the edge of next
* second and has interval of one second. */
spec.it_value.tv_sec = *now+1;
spec.it_value.tv_nsec = 0;
spec.it_interval.tv_sec = 1;
spec.it_interval.tv_nsec = 0;
GUARD(*fd = timerfd_create(CLOCK_REALTIME, 0));
GUARD(timerfd_settime(*fd, TFD_TIMER_ABSTIME, &spec, NULL));
}
int main(int argc, char *argv[])
{
int fd;
time_t now;
uint64_t ticks=0;
char date_buf[21];
date_buf[0] = '\0';
const char *date_p = date_buf;
init_clock(&fd, &now);
while (1) {
if (ticks == 0) {
// We have "processed" all seconds, wait for more
ssize_t s = read(fd, &ticks, sizeof(uint64_t));
if (s != sizeof(uint64_t)) {
errx(2,"Timer reading error");
}
}
ticks--;
now++;
if (*date_p == '\0') {
time_t future = now+19;
// Fill in date buffer
size_t len = strftime(date_buf, sizeof(date_buf),
"%F %H:%M:%S\n", localtime(&future));
if (len != 20 ) errx(3,"Date formatting error");
date_p = date_buf;
}
putchar(*date_p++);
fflush(stdout);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment