[yocto] [ptest-runner] utils.c: Prefer monotonic clock to calculate elapsed time

Jeffrey Pautler jeffrey.pautler at ni.com
Tue Oct 31 12:38:39 PDT 2017


The current implementation uses the system clock to calculate how long
a ptest has been running with no output. If a ptest changes the system
clock as part of the test, that can cause the current implementation
to falsely trigger a timeout or miss an actual timeout. It is
preferrable to use a monotonic clock for calculating elapsed time in
order to avoid these issues.

This change tries to use the monotonic clock first and falls back to
the realtime clock if the monotonic clock is not supported.

Signed-off-by: Jeffrey Pautler <jeffrey.pautler at ni.com>
---
 utils.c | 24 +++++++++++++++++-------
 1 file changed, 17 insertions(+), 7 deletions(-)

diff --git a/utils.c b/utils.c
index 6d65388..933eced 100644
--- a/utils.c
+++ b/utils.c
@@ -257,7 +257,8 @@ wait_child(const char *ptest_dir, const char *run_ptest, pid_t pid,
 		int timeout, int *fds, FILE **fps)
 {
 	struct pollfd pfds[2];
-	time_t sentinel;
+	struct timespec sentinel;
+	clockid_t clock = CLOCK_MONOTONIC;
 	int r;
 
 	int timeouted = 0;
@@ -269,7 +270,11 @@ wait_child(const char *ptest_dir, const char *run_ptest, pid_t pid,
 	pfds[1].fd = fds[1];
 	pfds[1].events = POLLIN;
 
-	sentinel = time(NULL);
+	if (clock_gettime(clock, &sentinel) == -1) {
+		clock = CLOCK_REALTIME;
+		clock_gettime(clock, &sentinel);
+	}
+
 	while (1) {
 		waitflags = WNOHANG;
 
@@ -288,11 +293,16 @@ wait_child(const char *ptest_dir, const char *run_ptest, pid_t pid,
 					fwrite(buf, n, 1, fps[1]);
 			}
 
-			sentinel = time(NULL);
-		} else if (timeout >= 0 && ((time(NULL) - sentinel) > timeout)) {
-			timeouted = 1;
-			kill(pid, SIGKILL);
-			waitflags = 0;
+			clock_gettime(clock, &sentinel);
+		} else if (timeout >= 0) {
+			struct timespec time;
+
+			clock_gettime(clock, &time);
+			if ((time.tv_sec - sentinel.tv_sec) > timeout) {
+				timeouted = 1;
+				kill(pid, SIGKILL);
+				waitflags = 0;
+			}
 		}
 
 		if (waitpid(pid, &status, waitflags) == pid)
-- 
2.7.4




More information about the yocto mailing list