get_cpu_count.c 1008 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Factored out of mpstat/iostat.
  4. *
  5. * Copyright (C) 2010 Marek Polacek <mmpolacek@gmail.com>
  6. *
  7. * Licensed under GPLv2, see file LICENSE in this source tree.
  8. */
  9. #include "libbb.h"
  10. /* Does str start with "cpu"? */
  11. int FAST_FUNC starts_with_cpu(const char *str)
  12. {
  13. return ((str[0] - 'c') | (str[1] - 'p') | (str[2] - 'u')) == 0;
  14. }
  15. /*
  16. * Get number of processors. Uses /proc/stat.
  17. * Return value 0 means one CPU and non SMP kernel.
  18. * Otherwise N means N processor(s) and SMP kernel.
  19. */
  20. unsigned FAST_FUNC get_cpu_count(void)
  21. {
  22. FILE *fp;
  23. char line[256];
  24. int proc_nr = -1;
  25. fp = xfopen_for_read("/proc/stat");
  26. while (fgets(line, sizeof(line), fp)) {
  27. if (!starts_with_cpu(line)) {
  28. if (proc_nr >= 0)
  29. break; /* we are past "cpuN..." lines */
  30. continue;
  31. }
  32. if (line[3] != ' ') { /* "cpuN" */
  33. int num_proc;
  34. if (sscanf(line + 3, "%u", &num_proc) == 1
  35. && num_proc > proc_nr
  36. ) {
  37. proc_nr = num_proc;
  38. }
  39. }
  40. }
  41. fclose(fp);
  42. return proc_nr + 1;
  43. }