3
0

nproc.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * Copyright (C) 2017 Denys Vlasenko <vda.linux@googlemail.com>
  3. *
  4. * Licensed under GPLv2, see LICENSE in this source tree
  5. */
  6. //config:config NPROC
  7. //config: bool "nproc (3.7 kb)"
  8. //config: default y
  9. //config: help
  10. //config: Print number of CPUs
  11. //applet:IF_NPROC(APPLET_NOFORK(nproc, nproc, BB_DIR_USR_BIN, BB_SUID_DROP, nproc))
  12. //kbuild:lib-$(CONFIG_NPROC) += nproc.o
  13. //usage:#define nproc_trivial_usage
  14. //usage: ""IF_LONG_OPTS("[--all] [--ignore=N]")
  15. //usage:#define nproc_full_usage "\n\n"
  16. //usage: "Print number of available CPUs"
  17. //usage: IF_LONG_OPTS(
  18. //usage: "\n"
  19. //usage: "\n --all Number of installed CPUs"
  20. //usage: "\n --ignore=N Exclude N CPUs"
  21. //usage: )
  22. #include <sched.h>
  23. #include "libbb.h"
  24. int nproc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  25. int nproc_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  26. {
  27. unsigned long mask[1024];
  28. int count = 0;
  29. #if ENABLE_LONG_OPTS
  30. int ignore = 0;
  31. int opts = getopt32long(argv, "\xfe:+",
  32. "ignore\0" Required_argument "\xfe"
  33. "all\0" No_argument "\xff"
  34. , &ignore
  35. );
  36. if (opts & (1 << 1)) {
  37. DIR *cpusd = opendir("/sys/devices/system/cpu");
  38. if (cpusd) {
  39. struct dirent *de;
  40. while (NULL != (de = readdir(cpusd))) {
  41. char *cpuid = strstr(de->d_name, "cpu");
  42. if (cpuid && isdigit(cpuid[strlen(cpuid) - 1]))
  43. count++;
  44. }
  45. IF_FEATURE_CLEAN_UP(closedir(cpusd);)
  46. }
  47. } else
  48. #endif
  49. if (sched_getaffinity(0, sizeof(mask), (void*)mask) == 0) {
  50. int i;
  51. for (i = 0; i < ARRAY_SIZE(mask); i++) {
  52. unsigned long m = mask[i];
  53. while (m) {
  54. if (m & 1)
  55. count++;
  56. m >>= 1;
  57. }
  58. }
  59. }
  60. IF_LONG_OPTS(count -= ignore;)
  61. if (count <= 0)
  62. count = 1;
  63. printf("%u\n", count);
  64. return 0;
  65. }