[PATCH xorg-gtest 1/4] process: use actual time for timeouts

Peter Hutterer peter.hutterer at who-t.net
Sun Oct 7 18:55:02 PDT 2012


loops and usleeps are nice and simple, but have a tendency to overrun the
actual timeouts given. Use the actual time instead.

Signed-off-by: Peter Hutterer <peter.hutterer at who-t.net>
---
 src/process.cpp | 19 +++++++++++++++++--
 1 file changed, 17 insertions(+), 2 deletions(-)

diff --git a/src/process.cpp b/src/process.cpp
index 4deea14..555e56b 100644
--- a/src/process.cpp
+++ b/src/process.cpp
@@ -30,6 +30,7 @@
 #include <sys/prctl.h>
 #include <sys/types.h>
 #include <sys/wait.h>
+#include <sys/time.h>
 #include <unistd.h>
 
 #include <algorithm>
@@ -127,16 +128,30 @@ void xorg::testing::Process::Start(const std::string& program, ...) {
 }
 
 bool xorg::testing::Process::WaitForExit(unsigned int timeout) {
-  for (unsigned int i = 0; i < timeout * 100; i++) {
+  struct timeval current;
+  struct timeval endtime;
+  struct timeval add;
+
+  if (gettimeofday(&current, NULL) != 0)
+    throw std::runtime_error("Failed to get the time");
+
+  add.tv_sec = timeout / 1000;
+  add.tv_usec = (timeout % 1000) * 1000;
+
+  timeradd(&current, &add, &endtime);
+
+  while (timercmp(&current, &endtime, <)) {
     int status;
     int pid = waitpid(Pid(), &status, WNOHANG);
 
+
     if (pid == Pid())
       return true;
     else if (pid == -1)
       return errno == ECHILD;
 
-      usleep(10);
+    if (gettimeofday(&current, NULL) != 0)
+      throw std::runtime_error("Failed to get the time");
   }
 
   return false;
-- 
1.7.11.4



More information about the xorg-devel mailing list