logo

utils-std

Collection of commonly available Unix tools git clone https://anongit.hacktivis.me/git/utils-std.git/

nproc.c (1911B)


  1. // utils-std: Collection of commonly available Unix tools
  2. // SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. // SPDX-License-Identifier: MPL-2.0
  4. // _SC_NPROCESSORS_CONF &_SC_NPROCESSORS_ONLN got added in POSIX.1-2024
  5. // https://www.austingroupbugs.net/view.php?id=339
  6. #define _DEFAULT_SOURCE
  7. // Sadly {Free,Net}BSD hides _SC_NPROCESSORS_{CONF,ONLN} if _POSIX_C_SOURCE is defined *sigh*
  8. // #define _POSIX_C_SOURCE 202405L
  9. #include "../config.h"
  10. #include "../libutils/getopt_nolong.h"
  11. #include <errno.h>
  12. #include <stdio.h> // printf
  13. #include <string.h> // strerror
  14. #include <unistd.h> // sysconf, getopt, opt*
  15. #ifdef HAS_GETOPT_LONG
  16. #include <getopt.h>
  17. #endif
  18. const char *argv0 = "nproc";
  19. static void
  20. usage(void)
  21. {
  22. fprintf(stderr, "Usage: nproc [-a]\n");
  23. }
  24. int
  25. main(int argc, char *argv[])
  26. {
  27. // currently available
  28. int target = _SC_NPROCESSORS_ONLN;
  29. const char *target_str = "_SC_NPROCESSORS_ONLN";
  30. #ifdef HAS_GETOPT_LONG
  31. // Strictly for GNUisms compatibility so no long-only options
  32. // clang-format off
  33. static struct option opts[] = {
  34. {"all", no_argument, NULL, 'a'},
  35. {0, 0, 0, 0},
  36. };
  37. // clang-format on
  38. // Need + as first character to get POSIX-style option parsing
  39. for(int c = -1; (c = getopt_long(argc, argv, "+:a", opts, NULL)) != -1;)
  40. #else
  41. for(int c = -1; (c = getopt_nolong(argc, argv, ":a")) != -1;)
  42. #endif
  43. {
  44. switch(c)
  45. {
  46. case 'a': // can be made available
  47. target = _SC_NPROCESSORS_CONF;
  48. target_str = "_SC_NPROCESSORS_CONF";
  49. break;
  50. case ':':
  51. fprintf(stderr, "%s: error: Missing operand for option: '-%c'\n", argv0, optopt);
  52. usage();
  53. return 1;
  54. case '?':
  55. GETOPT_UNKNOWN_OPT
  56. usage();
  57. return 1;
  58. }
  59. }
  60. long np = sysconf(target);
  61. if(np < 0)
  62. {
  63. fprintf(
  64. stderr, "%s: error: Failed getting sysconf '%s': %s\n", argv0, target_str, strerror(errno));
  65. return 1;
  66. }
  67. printf("%ld\n", np);
  68. return 0;
  69. }