From c96d21c7c073beedc037fb3e66e24c313dce2c13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E9=80=9A=E6=B4=B2?= Date: Tue, 10 Oct 2023 11:18:22 +0800 Subject: [PATCH] CPUUsage (Linux): count cpu cores separately --- src/detection/cpuusage/cpuusage_linux.c | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/src/detection/cpuusage/cpuusage_linux.c b/src/detection/cpuusage/cpuusage_linux.c index 78c64215e..ac73d39c8 100644 --- a/src/detection/cpuusage/cpuusage_linux.c +++ b/src/detection/cpuusage/cpuusage_linux.c @@ -1,14 +1,13 @@ #include "fastfetch.h" #include "detection/cpuusage/cpuusage.h" +#include "common/io/io.h" #include #include const char* ffGetCpuUsageInfo(uint64_t* inUseAll, uint64_t* totalAll) { - uint64_t user = 0, nice = 0, system = 0, idle = 0, iowait = 0, irq = 0, softirq = 0; - - FILE* procStat = fopen("/proc/stat", "r"); + FF_AUTO_CLOSE_FILE FILE* procStat = fopen("/proc/stat", "r"); if(procStat == NULL) { #ifdef __ANDROID__ @@ -17,16 +16,21 @@ const char* ffGetCpuUsageInfo(uint64_t* inUseAll, uint64_t* totalAll) return "fopen(\"""/proc/stat\", \"r\") == NULL"; #endif } + // Skip first line + if (fscanf(procStat, "cpu%*[^\n]\n") < 0) + return "fscanf() first line failed"; - if (fscanf(procStat, "cpu%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64, &user, &nice, &system, &idle, &iowait, &irq, &softirq) < 0) + *inUseAll = 0; + *totalAll = 0; + + uint64_t user = 0, nice = 0, system = 0, idle = 0, iowait = 0, irq = 0, softirq = 0; + while (fscanf(procStat, "cpu%*d%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64, &user, &nice, &system, &idle, &iowait, &irq, &softirq) == 7) { - fclose(procStat); - return "fscanf() failed"; + uint64_t inUse = user + nice + system; + uint64_t total = inUse + idle + iowait + irq + softirq; + *inUseAll += inUse; + *totalAll += total; } - *inUseAll = user + nice + system; - *totalAll = *inUseAll + idle + iowait + irq + softirq; - - fclose(procStat); return NULL; }