nproc.c (1480B)
- // 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 <errno.h>
- #include <stdio.h> // printf
- #include <string.h> // strerror
- #include <unistd.h> // sysconf, getopt, opt*
- 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";
- int c = -1;
- while((c = getopt(argc, argv, ":a")) != -1)
- {
- 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 '?':
- fprintf(stderr, "%s: error: Unrecognised option: '-%c'\n", argv0, optopt);
- 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;
- }