From 7fb2807d0c270fe15f9734cb9bb0b239f7df8975 Mon Sep 17 00:00:00 2001 From: apio Date: Sat, 7 Jan 2023 00:27:23 +0100 Subject: [PATCH] libc: Implement time() using clock_gettime(). The cool POSIX kids use clock_gettime() now because it has NANOSECONDS (and different clocks!), but ANSI C prefers this function. We can still implement it based on clock_gettime(), we just have to discard the NANOSECONDS. --- apps/app.c | 5 ++--- libc/include/time.h | 3 +++ libc/src/time.cpp | 10 ++++++++++ 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/apps/app.c b/apps/app.c index 73a9dbff..2e185b9b 100644 --- a/apps/app.c +++ b/apps/app.c @@ -16,9 +16,8 @@ int main() console_print(buffer); - struct timespec ts; - clock_gettime(CLOCK_REALTIME, &ts); - snprintf(buffer, sizeof(buffer), "Realtime clock: %ld s, %ld ns\n", ts.tv_sec, ts.tv_nsec); + time_t now = time(NULL); + snprintf(buffer, sizeof(buffer), "Realtime clock: %ld s\n", now); console_print(buffer); diff --git a/libc/include/time.h b/libc/include/time.h index 9a951da0..82eb7884 100644 --- a/libc/include/time.h +++ b/libc/include/time.h @@ -12,6 +12,9 @@ extern "C" /* Get the current value of a system clock. */ int clock_gettime(clockid_t id, struct timespec* ts); + /* Get the current wall clock time. */ + time_t time(time_t* tp); + #ifdef __cplusplus } #endif diff --git a/libc/src/time.cpp b/libc/src/time.cpp index aaa33f57..b33a3c6c 100644 --- a/libc/src/time.cpp +++ b/libc/src/time.cpp @@ -10,4 +10,14 @@ extern "C" long rc = syscall(SYS_clock_gettime, id, ts); __errno_return(rc, int); } + + time_t time(time_t* tp) + { + struct timespec ts; + if (clock_gettime(CLOCK_REALTIME, &ts) < 0) return (time_t)-1; + + if (tp) *tp = ts.tv_sec; + + return ts.tv_sec; + } }