nproc.c (1911B)
- // utils-std: Collection of commonly available Unix tools
- // SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
- // SPDX-License-Identifier: MPL-2.0
- // _SC_NPROCESSORS_CONF &_SC_NPROCESSORS_ONLN got added in POSIX.1-2024
- // https://www.austingroupbugs.net/view.php?id=339
- #define _DEFAULT_SOURCE
- // Sadly {Free,Net}BSD hides _SC_NPROCESSORS_{CONF,ONLN} if _POSIX_C_SOURCE is defined *sigh*
- // #define _POSIX_C_SOURCE 202405L
- #include "../config.h"
- #include "../libutils/getopt_nolong.h"
- #include <errno.h>
- #include <stdio.h> // printf
- #include <string.h> // strerror
- #include <unistd.h> // sysconf, getopt, opt*
- #ifdef HAS_GETOPT_LONG
- #include <getopt.h>
- #endif
- const char *argv0 = "nproc";
- static void
- usage(void)
- {
- fprintf(stderr, "Usage: nproc [-a]\n");
- }
- int
- main(int argc, char *argv[])
- {
- // currently available
- int target = _SC_NPROCESSORS_ONLN;
- const char *target_str = "_SC_NPROCESSORS_ONLN";
- #ifdef HAS_GETOPT_LONG
- // Strictly for GNUisms compatibility so no long-only options
- // clang-format off
- static struct option opts[] = {
- {"all", no_argument, NULL, 'a'},
- {0, 0, 0, 0},
- };
- // clang-format on
- // Need + as first character to get POSIX-style option parsing
- for(int c = -1; (c = getopt_long(argc, argv, "+:a", opts, NULL)) != -1;)
- #else
- for(int c = -1; (c = getopt_nolong(argc, argv, ":a")) != -1;)
- #endif
- {
- switch(c)
- {
- case 'a': // can be made available
- target = _SC_NPROCESSORS_CONF;
- target_str = "_SC_NPROCESSORS_CONF";
- break;
- case ':':
- fprintf(stderr, "%s: error: Missing operand for option: '-%c'\n", argv0, optopt);
- usage();
- return 1;
- case '?':
- GETOPT_UNKNOWN_OPT
- usage();
- return 1;
- }
- }
- long np = sysconf(target);
- if(np < 0)
- {
- fprintf(
- stderr, "%s: error: Failed getting sysconf '%s': %s\n", argv0, target_str, strerror(errno));
- return 1;
- }
- printf("%ld\n", np);
- return 0;
- }