commit:     fa942450e3b289057881a60fd98a9d4b35d99604
Author:     Kerin Millar <kfm <AT> plushkava <DOT> net>
AuthorDate: Fri Jun  7 13:00:01 2024 +0000
Commit:     Sam James <sam <AT> gentoo <DOT> org>
CommitDate: Wed Jun 12 07:06:42 2024 +0000
URL:        
https://gitweb.gentoo.org/proj/gentoo-functions.git/commit/?id=fa942450

Add the get_nprocs() function

It stands a good chance of printing a useful value, even in the case
that nproc(1) from coreutils is unavailable.

Signed-off-by: Kerin Millar <kfm <AT> plushkava.net>

 functions.sh   | 20 ++++++++++++++++++++
 test-functions | 12 ++++++++++++
 2 files changed, 32 insertions(+)

diff --git a/functions.sh b/functions.sh
index 504ee9e..60a4b2e 100644
--- a/functions.sh
+++ b/functions.sh
@@ -460,6 +460,26 @@ newest()
        _select_by_mtime -r "$@"
 }
 
+#
+# Tries to determine the number of available processors. Falls back to trying 
to
+# determine the number of online processors in a way that is somewhat portable.
+#
+get_nprocs()
+{
+       if nproc 2>/dev/null; then
+               # The nproc(1) utility is provided by GNU coreutils. It has the
+               # advantage of acknowledging the effect of sched_setaffinity(2).
+               true
+       elif getconf _NPROCESSORS_ONLN 2>/dev/null; then
+               # This is a non-standard extension. Nevertheless, it works for
+               # glibc, musl-utils, macOS, FreeBSD, NetBSD and OpenBSD.
+               true
+       else
+               warn "get_nprocs: failed to determine the number of processors"
+               false
+       fi
+}
+
 #
 # Considers one or more pathnames and prints the one having the oldest
 # modification time. If at least one parameter is provided, all parameters 
shall

diff --git a/test-functions b/test-functions
index 813d524..c734141 100755
--- a/test-functions
+++ b/test-functions
@@ -544,6 +544,17 @@ test_whenceforth() {
        iterate_tests 4 "$@"
 }
 
+test_get_nprocs() {
+       set -- eq 0
+
+       callback() {
+               shift
+               test_description="get_nprocs"
+               nproc=$(get_nprocs) && is_int "${nproc}" && test "${nproc}" -gt 0
+       }
+
+       iterate_tests 2 "$@"
+}
 
 iterate_tests() {
        slice_width=$1
@@ -610,6 +621,7 @@ test_newest || rc=1
 test_trim || rc=1
 test_hr || rc=1
 test_whenceforth || rc=1
+test_get_nprocs || rc=1
 
 cleanup_tmpdir
 

Reply via email to