logo

utils-std

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

nproc.c (1480B)


  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 <errno.h>
  10. #include <stdio.h> // printf
  11. #include <string.h> // strerror
  12. #include <unistd.h> // sysconf, getopt, opt*
  13. const char *argv0 = "nproc";
  14. static void
  15. usage(void)
  16. {
  17. fprintf(stderr, "Usage: nproc [-a]\n");
  18. }
  19. int
  20. main(int argc, char *argv[])
  21. {
  22. // currently available
  23. int target = _SC_NPROCESSORS_ONLN;
  24. const char *target_str = "_SC_NPROCESSORS_ONLN";
  25. int c = -1;
  26. while((c = getopt(argc, argv, ":a")) != -1)
  27. {
  28. switch(c)
  29. {
  30. case 'a': // can be made available
  31. target = _SC_NPROCESSORS_CONF;
  32. target_str = "_SC_NPROCESSORS_CONF";
  33. break;
  34. case ':':
  35. fprintf(stderr, "%s: error: Missing operand for option: '-%c'\n", argv0, optopt);
  36. usage();
  37. return 1;
  38. case '?':
  39. fprintf(stderr, "%s: error: Unrecognised option: '-%c'\n", argv0, optopt);
  40. usage();
  41. return 1;
  42. }
  43. }
  44. long np = sysconf(target);
  45. if(np < 0)
  46. {
  47. fprintf(
  48. stderr, "%s: error: Failed getting sysconf '%s': %s\n", argv0, target_str, strerror(errno));
  49. return 1;
  50. }
  51. printf("%ld\n", np);
  52. return 0;
  53. }