Code

Implemented better loop-timing using `nanosleep(2)'.
authorocto <octo>
Tue, 21 Mar 2006 12:43:40 +0000 (12:43 +0000)
committerocto <octo>
Tue, 21 Mar 2006 12:43:40 +0000 (12:43 +0000)
src/collectd.c

index 47745cb0c05929dd2fac3047ead5f0908dc5f31d..6513cd4997093107e1b9d9d971edcdd195beb161 100644 (file)
@@ -148,9 +148,12 @@ static void exit_usage (char *name)
 
 static int start_client (void)
 {
-       int sleepingtime;
        int step;
 
+       struct timeval tv_now;
+       struct timeval tv_next;
+       struct timespec ts_wait;
+
        step = atoi (COLLECTD_STEP);
        if (step <= 0)
                step = 10;
@@ -178,18 +181,37 @@ static int start_client (void)
 
        while (loop == 0)
        {
-               curtime = time (NULL);
+               if (gettimeofday (&tv_next, NULL) < 0)
+               {
+                       syslog (LOG_ERR, "gettimeofday failed: %s", strerror (errno));
+                       return (-1);
+               }
+               tv_next.tv_sec += step;
+
 #if HAVE_LIBKSTAT
                update_kstat ();
 #endif
                plugin_read_all ();
 
-               sleepingtime = step;
-               while (sleepingtime != 0)
+               if (gettimeofday (&tv_now, NULL) < 0)
+               {
+                       syslog (LOG_ERR, "gettimeofday failed: %s", strerror (errno));
+                       return (-1);
+               }
+
+               if (timeval_sub_timespec (&tv_next, &tv_now, &ts_wait) != 0)
                {
-                       if (loop != 0)
+                       syslog (LOG_WARNING, "No sleeping because `timeval_sub_timespec' returned non-zero!");
+                       continue;
+               }
+
+               while (nanosleep (&ts_wait, &ts_wait) == -1)
+               {
+                       if (errno != EINTR)
+                       {
+                               syslog (LOG_ERR, "nanosleep failed: %s", strerror (errno));
                                break;
-                       sleepingtime = sleep (sleepingtime);
+                       }
                }
        }