From c9b9750a0e2a85d3d045cc8d0217d4605f2d7989 Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Mon, 16 Aug 2010 02:49:21 +0200 Subject: libbb: factor out common code from mpstat/iostat Signed-off-by: Denys Vlasenko --- libbb/get_cpu_count.c | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 libbb/get_cpu_count.c (limited to 'libbb/get_cpu_count.c') diff --git a/libbb/get_cpu_count.c b/libbb/get_cpu_count.c new file mode 100644 index 000000000..a0dcb45f5 --- /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 + * + * 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; +} -- cgit v1.2.3