nproc.c (1080B)
- // Collection of Unix tools, comparable to coreutils
- // SPDX-FileCopyrightText: 2017-2022 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
- // SPDX-License-Identifier: MPL-2.0
- #define _DEFAULT_SOURCE // _SC_NPROCESSORS_CONF
- #include <stdio.h> // printf
- #include <unistd.h> // sysconf, getopt, opt*
- void
- usage()
- {
- fprintf(stderr, "Usage: nproc [-a]\n");
- }
- int
- main(int argc, char *argv[])
- {
- // _SC_NPROCESSORS_CONF &_SC_NPROCESSORS_ONLN aren't in POSIX yet but have been accepted
- // https://www.austingroupbugs.net/view.php?id=339
- int target = _SC_NPROCESSORS_ONLN;
- int c;
- while((c = getopt(argc, argv, ":a")) != EOF)
- {
- switch(c)
- {
- case 'a': // all processors
- target = _SC_NPROCESSORS_CONF;
- break;
- case ':':
- fprintf(stderr, "nproc: Error: Missing operand for option: '-%c'\n", optopt);
- usage();
- return 1;
- case '?':
- fprintf(stderr, "nproc: Error: Unrecognised option: '-%c'\n", optopt);
- usage();
- return 1;
- }
- }
- long np = sysconf(target);
- if(np < 0)
- {
- perror("sysconf");
- return 1;
- }
- printf("%ld\n", np);
- return 0;
- }