mirror of
https://github.com/fastfetch-cli/fastfetch.git
synced 2026-09-13 02:42:09 +02:00
fix(CPUUsage): fix reading procfs files and simplify data parsing
This commit is contained in:
@@ -7,30 +7,42 @@
|
||||
|
||||
const char* ffGetCpuUsageInfo(FFlist* cpuTimes)
|
||||
{
|
||||
FF_AUTO_CLOSE_FILE FILE* procStat = fopen("/proc/stat", "r");
|
||||
if(procStat == NULL)
|
||||
char buf[PROC_FILE_BUFFSIZ];
|
||||
ssize_t nRead = ffReadFileData("/proc/stat", sizeof(buf) - 1, buf);
|
||||
if(nRead < 0)
|
||||
{
|
||||
#ifdef __ANDROID__
|
||||
return "Accessing \"/proc/stat\" is restricted on Android O+";
|
||||
#else
|
||||
return "fopen(\"""/proc/stat\", \"r\") == NULL";
|
||||
return "ffReadFileData(\"/proc/stat\", sizeof(buf) - 1, buf) failed";
|
||||
#endif
|
||||
}
|
||||
buf[nRead] = '\0';
|
||||
|
||||
// Skip first line
|
||||
if (fscanf(procStat, "cpu%*[^\n]\n") < 0)
|
||||
return "fscanf() first line failed";
|
||||
char *start = NULL;
|
||||
if((start = strchr(buf, '\n')) == NULL)
|
||||
return "skip first line failed";
|
||||
++start;
|
||||
|
||||
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 "%*[^\n]\n", &user, &nice, &system, &idle, &iowait, &irq, &softirq) == 7)
|
||||
char *token = NULL;
|
||||
while ((token = strchr(start, '\n')))
|
||||
{
|
||||
uint64_t inUse = user + nice + system;
|
||||
uint64_t total = inUse + idle + iowait + irq + softirq;
|
||||
if(sscanf(start, "cpu%*d%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%*[^\n]\n", &user, &nice, &system, &idle, &iowait, &irq, &softirq) == 7)
|
||||
{
|
||||
uint64_t inUse = user + nice + system;
|
||||
uint64_t total = inUse + idle + iowait + irq + softirq;
|
||||
|
||||
FFCpuUsageInfo* info = (FFCpuUsageInfo*) ffListAdd(cpuTimes);
|
||||
*info = (FFCpuUsageInfo) {
|
||||
.inUseAll = (uint64_t)inUse,
|
||||
.totalAll = (uint64_t)total,
|
||||
};
|
||||
FFCpuUsageInfo* info = (FFCpuUsageInfo*) ffListAdd(cpuTimes);
|
||||
*info = (FFCpuUsageInfo) {
|
||||
.inUseAll = (uint64_t)inUse,
|
||||
.totalAll = (uint64_t)total,
|
||||
};
|
||||
}
|
||||
else
|
||||
break; // because we read the whole /proc/stat, we can safely quit when the line does not start with "cpuN"
|
||||
start = token + 1;
|
||||
}
|
||||
|
||||
return NULL;
|
||||
|
||||
Reference in New Issue
Block a user