Skip to content

Instantly share code, notes, and snippets.

@aabccd021
Last active July 27, 2025 01:50
Show Gist options
  • Save aabccd021/c1538287fce3a56d3d2127b54deec91c to your computer and use it in GitHub Desktop.
Save aabccd021/c1538287fce3a56d3d2127b54deec91c to your computer and use it in GitHub Desktop.
Mock time in unix process
console.log("System time is:", new Date().toISOString());
#define _GNU_SOURCE
#include <stdio.h>
#include <dlfcn.h>
#include <time.h>
#include <sys/time.h>
#include <stdlib.h>
#include <string.h>
time_t read_time_from_file() {
static char path[4096];
const char *state = getenv("NETERO_STATE");
if (!state) return time(NULL);
size_t len = strlen(state);
if (len + 9 >= sizeof(path)) return time(NULL);
strcpy(path, state);
if (path[len-1] != '/') {
path[len] = '/';
path[len+1] = '\0';
len += 1;
}
strcat(path, "now.txt");
FILE *f = fopen(path, "r");
if (!f) return time(NULL);
char buf[64];
if (!fgets(buf, sizeof(buf), f)) {
fclose(f);
return time(NULL);
}
fclose(f);
struct tm tm = {0};
if (!strptime(buf, "%Y-%m-%dT%H:%M:%SZ", &tm)) {
return time(NULL);
}
time_t t = timegm(&tm);
return t;
}
time_t time(time_t *tloc) {
time_t t = read_time_from_file();
if (tloc) *tloc = t;
return t;
}
int gettimeofday(struct timeval *tv, void *tz) {
time_t t = read_time_from_file();
if (tv) {
tv->tv_sec = t;
tv->tv_usec = 0;
}
if (tz) {
struct timezone *ptz = (struct timezone *)tz;
ptz->tz_minuteswest = 0;
ptz->tz_dsttime = 0;
}
return 0;
}
nix run nixpkgs#gcc_multi -- -shared -fPIC -o libmocktime.so mock_time.c -ldl
nix shell nixpkgs#nodejs --command watch LD_PRELOAD=$PWD/libmocktime.so node demo_time.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment