]> sourceware.org Git - glibc.git/commitdiff
Linux: implement getloadavg(3) using sysinfo(2)
authorCristian Rodríguez <crrodriguez@opensuse.org>
Fri, 6 Aug 2021 19:17:48 +0000 (15:17 -0400)
committerAdhemerval Zanella <adhemerval.zanella@linaro.org>
Fri, 8 Oct 2021 12:52:19 +0000 (09:52 -0300)
Signed-off-by: Cristian Rodríguez <crrodriguez@opensuse.org>
Reviewed-by: Adhemerval Zanella <adhemerval.zanella@linaro.org>
sysdeps/unix/sysv/linux/getloadavg.c

index e50cc396e7f20b298a4d27b7bc339cd82bbed285..6f3e5b93a8f2cb3cc2153332b9c27ea87e78c0a1 100644 (file)
@@ -1,4 +1,4 @@
-/* Get system load averages.  Linux (/proc/loadavg) version.
+/* Get system load averages.  Linux version.
    Copyright (C) 1999-2021 Free Software Foundation, Inc.
    This file is part of the GNU C Library.
 
    License along with the GNU C Library; if not, see
    <https://www.gnu.org/licenses/>.  */
 
-#include <errno.h>
-#include <fcntl.h>
-#include <locale.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <not-cancel.h>
+#include <array_length.h>
+#include <sys/param.h>
+#include <sys/sysinfo.h>
 
 /* Put the 1 minute, 5 minute and 15 minute load averages
    into the first NELEM elements of LOADAVG.
    Return the number written (never more than 3, but may be less than NELEM),
    or -1 if an error occurred.  */
 
+#define CLAMP(v, lo, hi) MIN (MAX (v, lo), hi)
+
+#define SYSINFO_LOADS_SCALE (1 << SI_LOAD_SHIFT)
+
 int
 getloadavg (double loadavg[], int nelem)
 {
-  int fd;
+  struct sysinfo info;
 
-  fd = __open_nocancel ("/proc/loadavg", O_RDONLY);
-  if (fd < 0)
+  if (__sysinfo (&info) != 0)
     return -1;
-  else
-    {
-      char buf[65], *p;
-      ssize_t nread;
-      int i;
 
-      nread = __read_nocancel (fd, buf, sizeof buf - 1);
-      __close_nocancel_nostatus (fd);
-      if (nread <= 0)
-       return -1;
-      buf[nread - 1] = '\0';
+  nelem = CLAMP (nelem, 0, array_length (info.loads));
 
-      if (nelem > 3)
-       nelem = 3;
-      p = buf;
-      for (i = 0; i < nelem; ++i)
-       {
-         char *endp;
-         loadavg[i] = __strtod_l (p, &endp, _nl_C_locobj_ptr);
-         if (endp == p)
-           /* This should not happen.  The format of /proc/loadavg
-              must have changed.  Don't return with what we have,
-              signal an error.  */
-           return -1;
-         p = endp;
-       }
+  for (int i = 0; i < nelem; i++)
+    loadavg[i] = (double) info.loads[i] / SYSINFO_LOADS_SCALE;
 
-      return i;
-    }
+  return nelem;
 }
This page took 0.042225 seconds and 5 git commands to generate.