diff options
author | Kerin Millar <kfm@plushkava.net> | 2024-06-07 14:00:01 +0100 |
---|---|---|
committer | Kerin Millar <kfm@plushkava.net> | 2024-06-12 08:06:42 +0100 |
commit | fa942450e3b289057881a60fd98a9d4b35d99604 (patch) | |
tree | 8d762a68b7b66227d92da3477d69f178b8103cb4 | |
parent | Add the whenceforth() function as a type -P alternative (diff) | |
download | gentoo-functions-fa942450e3b289057881a60fd98a9d4b35d99604.tar.gz gentoo-functions-fa942450e3b289057881a60fd98a9d4b35d99604.tar.bz2 gentoo-functions-fa942450e3b289057881a60fd98a9d4b35d99604.zip |
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@plushkava.net>
-rw-r--r-- | functions.sh | 20 | ||||
-rwxr-xr-x | test-functions | 12 |
2 files changed, 32 insertions, 0 deletions
diff --git a/functions.sh b/functions.sh index 504ee9e..60a4b2e 100644 --- a/functions.sh +++ b/functions.sh @@ -461,6 +461,26 @@ newest() } # +# 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 # be considered as pathnames to be compared to one another. Otherwise, the 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 |