nproc.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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"
  8. //config: default y
  9. //config: help
  10. //config: Print number of CPUs
  11. //applet:IF_NPROC(APPLET(nproc, BB_DIR_USR_BIN, BB_SUID_DROP))
  12. //kbuild:lib-$(CONFIG_NPROC) += nproc.o
  13. //usage:#define nproc_trivial_usage
  14. //usage: ""
  15. //TODO: "[--all] [--ignore=N]"
  16. //usage:#define nproc_full_usage "\n\n"
  17. //usage: "Print number of CPUs"
  18. #include <sched.h>
  19. #include "libbb.h"
  20. int nproc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  21. int nproc_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  22. {
  23. unsigned long mask[1024];
  24. unsigned i, count = 0;
  25. //applet_long_options = ...;
  26. //getopt32(argv, "");
  27. //if --all, count /sys/devices/system/cpu/cpuN dirs, else:
  28. if (sched_getaffinity(0, sizeof(mask), (void*)mask) == 0) {
  29. for (i = 0; i < ARRAY_SIZE(mask); i++) {
  30. unsigned long m = mask[i];
  31. while (m) {
  32. if (m & 1)
  33. count++;
  34. m >>= 1;
  35. }
  36. }
  37. }
  38. if (count == 0)
  39. count++;
  40. printf("%u\n", count);
  41. return 0;
  42. }