nproc.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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.9 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 "libbb.h"
  23. int nproc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  24. int nproc_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  25. {
  26. int count = 0;
  27. #if ENABLE_LONG_OPTS
  28. int ignore = 0;
  29. int opts = getopt32long(argv, "\xfe:+",
  30. "ignore\0" Required_argument "\xfe"
  31. "all\0" No_argument "\xff"
  32. , &ignore
  33. );
  34. if (opts & (1 << 1)) {
  35. DIR *cpusd = opendir("/sys/devices/system/cpu");
  36. if (cpusd) {
  37. struct dirent *de;
  38. while (NULL != (de = readdir(cpusd))) {
  39. char *cpuid = strstr(de->d_name, "cpu");
  40. if (cpuid && isdigit(cpuid[strlen(cpuid) - 1]))
  41. count++;
  42. }
  43. IF_FEATURE_CLEAN_UP(closedir(cpusd);)
  44. }
  45. } else
  46. #endif
  47. {
  48. int i;
  49. unsigned sz = 2 * 1024;
  50. unsigned long *mask = get_malloc_cpu_affinity(0, &sz);
  51. sz /= sizeof(long);
  52. for (i = 0; i < sz; i++) {
  53. if (mask[i] != 0) /* most mask[i] are usually 0 */
  54. count += bb_popcnt_long(mask[i]);
  55. }
  56. IF_FEATURE_CLEAN_UP(free(mask);)
  57. }
  58. IF_LONG_OPTS(count -= ignore;)
  59. if (count <= 0)
  60. count = 1;
  61. printf("%u\n", count);
  62. return 0;
  63. }