nproc: Work better on Linux when /proc and /sys are not mounted.
authorBruno Haible <bruno@clisp.org>
Mon, 11 Jan 2010 01:16:04 +0000 (02:16 +0100)
committerBruno Haible <bruno@clisp.org>
Mon, 11 Jan 2010 19:19:31 +0000 (20:19 +0100)
ChangeLog
lib/nproc.c

index f07170a623ea0105af55ed1a5aafe2aae3b4a1df..3509cdd579ca16ba8b334307f43b70f4c171844b 100644 (file)
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,5 +1,12 @@
 2010-01-10  Bruno Haible  <bruno@clisp.org>
 
+       nproc: Work better on Linux when /proc and /sys are not mounted.
+       * lib/nproc.c (num_processors): Use num_processors_via_affinity_mask ()
+       as lower bound when, on glibc/Linux systems,
+       sysconf (_SC_NPROCESSORS_CONF) returns 1.
+       Suggested by Pádraig Brady <P@draigbrady.com>.
+       Reported by Dmitry V. Levin <ldv@altlinux.org>.
+
        nproc: Refactor.
        * lib/nproc.c (num_processors_via_affinity_mask): New function,
        extracted from num_processors.
index b72d7215779b1586f467efba35164e5102bc1d13..90b568eb37ff083073b595b5592a1830eca44cf0 100644 (file)
@@ -239,7 +239,12 @@ num_processors (enum nproc_query query)
      The first number is the number of CPUs configured in the system.
      The second number is the number of CPUs available to the scheduler.
      The third number is the number of CPUs available to the current process.
-   */
+
+     Note! On Linux systems with glibc, the first and second number come from
+     the /sys and /proc file systems (see
+     glibc/sysdeps/unix/sysv/linux/getsysstats.c).
+     In some situations these file systems are not mounted, and the sysconf
+     call returns 1, which does not reflect the reality.  */
 
   if (query == NPROC_CURRENT)
     {
@@ -266,6 +271,22 @@ num_processors (enum nproc_query query)
       { /* This works on glibc, MacOS X 10.5, FreeBSD, AIX, OSF/1, Solaris,
            Cygwin, Haiku.  */
         long int nprocs = sysconf (_SC_NPROCESSORS_CONF);
+
+# if __GLIBC__ >= 2 && defined __linux__
+        /* On Linux systems with glibc, this information comes from the /sys and
+           /proc file systems (see glibc/sysdeps/unix/sysv/linux/getsysstats.c).
+           In some situations these file systems are not mounted, and the
+           sysconf call returns 1.  But we wish to guarantee that
+           num_processors (NPROC_ALL) >= num_processors (NPROC_CURRENT).  */
+        if (nprocs == 1)
+          {
+            unsigned long nprocs_current = num_processors_via_affinity_mask ();
+
+            if (nprocs_current > 0)
+              nprocs = nprocs_current;
+          }
+# endif
+
         if (nprocs > 0)
           return nprocs;
       }