logo

utils

~/.local/bin tools and git-hooks git clone https://hacktivis.me/git/utils.git

nproc.c (1080B)


  1. // Collection of Unix tools, comparable to coreutils
  2. // SPDX-FileCopyrightText: 2017-2022 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. // SPDX-License-Identifier: MPL-2.0
  4. #define _DEFAULT_SOURCE // _SC_NPROCESSORS_CONF
  5. #include <stdio.h> // printf
  6. #include <unistd.h> // sysconf, getopt, opt*
  7. void
  8. usage()
  9. {
  10. fprintf(stderr, "Usage: nproc [-a]\n");
  11. }
  12. int
  13. main(int argc, char *argv[])
  14. {
  15. // _SC_NPROCESSORS_CONF &_SC_NPROCESSORS_ONLN aren't in POSIX yet but have been accepted
  16. // https://www.austingroupbugs.net/view.php?id=339
  17. int target = _SC_NPROCESSORS_ONLN;
  18. int c;
  19. while((c = getopt(argc, argv, ":a")) != EOF)
  20. {
  21. switch(c)
  22. {
  23. case 'a': // all processors
  24. target = _SC_NPROCESSORS_CONF;
  25. break;
  26. case ':':
  27. fprintf(stderr, "nproc: Error: Missing operand for option: '-%c'\n", optopt);
  28. usage();
  29. return 1;
  30. case '?':
  31. fprintf(stderr, "nproc: Error: Unrecognised option: '-%c'\n", optopt);
  32. usage();
  33. return 1;
  34. }
  35. }
  36. long np = sysconf(target);
  37. if(np < 0)
  38. {
  39. perror("sysconf");
  40. return 1;
  41. }
  42. printf("%ld\n", np);
  43. return 0;
  44. }