summaryrefslogtreecommitdiff
path: root/libbb
diff options
context:
space:
mode:
Diffstat (limited to 'libbb')
-rw-r--r--libbb/Kbuild.src3
-rw-r--r--libbb/get_cpu_count.c47
2 files changed, 50 insertions, 0 deletions
diff --git a/libbb/Kbuild.src b/libbb/Kbuild.src
index 5c56700..6081ebe 100644
--- a/libbb/Kbuild.src
+++ b/libbb/Kbuild.src
@@ -157,6 +157,9 @@ lib-$(CONFIG_MOUNT) += find_mount_point.o
lib-$(CONFIG_HWCLOCK) += rtc.o
lib-$(CONFIG_RTCWAKE) += rtc.o
+lib-$(CONFIG_IOSTAT) += get_cpu_count.o
+lib-$(CONFIG_MPSTAT) += get_cpu_count.o
+
# We shouldn't build xregcomp.c if we don't need it - this ensures we don't
# require regex.h to be in the include dir even if we don't need it thereby
# allowing us to build busybox even if uclibc regex support is disabled.
diff --git a/libbb/get_cpu_count.c b/libbb/get_cpu_count.c
new file mode 100644
index 0000000..a0dcb45
--- /dev/null
+++ b/libbb/get_cpu_count.c
@@ -0,0 +1,47 @@
+/* vi: set sw=4 ts=4: */
+/*
+ * Factored out of mpstat/iostat.
+ *
+ * Copyright (C) 2010 Marek Polacek <mmpolacek@gmail.com>
+ *
+ * Licensed under GPLv2, see file License in this tarball for details.
+ */
+#include "libbb.h"
+
+/* Does str start with "cpu"? */
+int FAST_FUNC starts_with_cpu(const char *str)
+{
+ return ((str[0] - 'c') | (str[1] - 'p') | (str[2] - 'u')) == 0;
+}
+
+/*
+ * Get number of processors. Uses /proc/stat.
+ * Return value 0 means one CPU and non SMP kernel.
+ * Otherwise N means N processor(s) and SMP kernel.
+ */
+unsigned FAST_FUNC get_cpu_count(void)
+{
+ FILE *fp;
+ char line[256];
+ int proc_nr = -1;
+
+ fp = xfopen_for_read("/proc/stat");
+ while (fgets(line, sizeof(line), fp)) {
+ if (!starts_with_cpu(line)) {
+ if (proc_nr >= 0)
+ break; /* we are past "cpuN..." lines */
+ continue;
+ }
+ if (line[3] != ' ') { /* "cpuN" */
+ int num_proc;
+ if (sscanf(line + 3, "%u", &num_proc) == 1
+ && num_proc > proc_nr
+ ) {
+ proc_nr = num_proc;
+ }
+ }
+ }
+
+ fclose(fp);
+ return proc_nr + 1;
+}