nproc.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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 (248 bytes)"
  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: ""
  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. //getopt32(argv, "");
  26. //if --all, count /sys/devices/system/cpu/cpuN dirs, else:
  27. if (sched_getaffinity(0, sizeof(mask), (void*)mask) == 0) {
  28. for (i = 0; i < ARRAY_SIZE(mask); i++) {
  29. unsigned long m = mask[i];
  30. while (m) {
  31. if (m & 1)
  32. count++;
  33. m >>= 1;
  34. }
  35. }
  36. }
  37. if (count == 0)
  38. count++;
  39. printf("%u\n", count);
  40. return 0;
  41. }