From 055b81f6a10c73b3e2013cd0a0f5fb4cec4fb6c1 Mon Sep 17 00:00:00 2001 From: Aleksei Vereshchagin Date: Tue, 4 Sep 2018 18:31:44 +0300 Subject: [PATCH] Fix CPU count calculation for one-CPU systems --- proc_stat.c | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/proc_stat.c b/proc_stat.c index 3a6a366..1fc53f2 100644 --- a/proc_stat.c +++ b/proc_stat.c @@ -80,15 +80,29 @@ static void write_proc_stat(FILE *stat_file_out, int pid, int timeout_usec, int uninit_write_proc_stat_context(&c); return; } - int tmp, ncpu; - if (fscanf(c.cpuf, "%d-%d\n", &tmp, &ncpu) < 2) { - log_system_error("fscanf(cpuf) failed"); - uninit_write_proc_stat_context(&c); - return; + unsigned int tmp = -1; + unsigned int ncpu = -1; + errno = 0; + + if (fscanf(c.cpuf, "%u-%u\n", &tmp, &ncpu) == 2) { + ncpu = ncpu - tmp + 1; + } else { + rewind(c.cpuf); + if (fscanf(c.cpuf, "%u\n", &ncpu) == 1) { + ncpu = ncpu + 1; + } else { + if (errno) { + log_system_error("fscanf(cpuf) failed"); + } else { + log_error("fscanf(cpuf) parsing error"); + } + uninit_write_proc_stat_context(&c); + return; + } } + fclose(c.cpuf); c.cpuf = NULL; - ncpu = ncpu - tmp + 1; long psize = sysconf(_SC_PAGESIZE); if (fprintf(stat_file_out, "psize %ld ncpu %d\n", psize, ncpu) < 0) { -- 2.34.1