clogger RubyGem user+dev discussion/patches/pulls/bugs/help
 help / color / mirror / code / Atom feed
* [PATCH] workaround for time(2) being non-monotonic
@ 2023-03-19 20:24 Eric Wong
  0 siblings, 0 replies; only message in thread
From: Eric Wong @ 2023-03-19 20:24 UTC (permalink / raw)
  To: clogger-public

Apparently, time(2) may go backwards in the first 1 - 2.5ms of
every second since Linux + glibc 2.31+ (and some proprietary
OSes).  Use clock_gettime(2) with CLOCK_REALTIME to workaround
the problem at the cost of a slight performance hit(*).  While git
will likely use gettimeofday(2) for compatibility with
proprietary OSes, gettimeofday(2) was declared obsolete in
POSIX.1-2008 and we don't support proprietary OSes.

(*) https://inbox.sourceware.org/libc-alpha/87ttywq0je.fsf@oldenburg.str.redhat.com/
Link: https://lore.kernel.org/git/20230319064353.686226-3-eggert@cs.ucla.edu/T/
---
 ext/clogger_ext/clogger.c | 18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)

diff --git a/ext/clogger_ext/clogger.c b/ext/clogger_ext/clogger.c
index 7989472..23aea39 100644
--- a/ext/clogger_ext/clogger.c
+++ b/ext/clogger_ext/clogger.c
@@ -475,9 +475,21 @@ static void append_request_length(struct clogger *c)
 	}
 }
 
+/*
+ * time(2) may slip backwards, so use CLOCK_REALTIME for accuracy
+ * https://lore.kernel.org/git/20230319064353.686226-3-eggert@cs.ucla.edu/T/
+ */
+static time_t cur_time(void)
+{
+	struct timespec now;
+
+	(void)clock_gettime(CLOCK_REALTIME, &now);
+	return now.tv_sec;
+}
+
 static long local_gmtoffset(struct tm *tm)
 {
-	time_t t = time(NULL);
+	time_t t = cur_time();
 
 	tzset();
 	localtime_r(&t, tm);
@@ -537,7 +549,7 @@ static void append_time_utc(struct clogger *c)
 	char buf[sizeof("01/Jan/1970:00:00:00 +0000")];
 	struct tm tm;
 	int nr;
-	time_t t = time(NULL);
+	time_t t = cur_time();
 
 	gmtime_r(&t, &tm);
 	nr = snprintf(buf, sizeof(buf),
@@ -556,7 +568,7 @@ append_time(struct clogger *c, enum clogger_opcode op, VALUE fmt, VALUE buf)
 	size_t buf_size = RSTRING_LEN(buf) + 1; /* "\0" */
 	size_t nr;
 	struct tm tmp;
-	time_t t = time(NULL);
+	time_t t = cur_time();
 
 	if (op == CL_OP_TIME_LOCAL)
 		localtime_r(&t, &tmp);

^ permalink raw reply related	[flat|nested] only message in thread

only message in thread, other threads:[~2023-03-19 20:24 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2023-03-19 20:24 [PATCH] workaround for time(2) being non-monotonic Eric Wong

Code repositories for project(s) associated with this public inbox

	https://yhbt.net/clogger.git/

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).