master ohmu/fastfetch-openbsd / src / detection / cpuusage / cpuusage_linux.c
ohmu  ·  2026-10-15
 1#include "fastfetch.h"
 2#include "detection/cpuusage/cpuusage.h"
 3#include "common/debug.h"
 4#include "common/io.h"
 5
 6#include <stdio.h>
 7#include <inttypes.h>
 8
 9const char* ffGetCpuUsageInfo(FFlist* cpuTimes) {
10    char buf[PROC_FILE_BUFFSIZ];
11    ssize_t nRead = ffReadFileData("/proc/stat", ARRAY_SIZE(buf) - 1, buf);
12    if (nRead < 0) {
13        FF_DEBUG("Reading \"/proc/stat\" failed: %s", strerror(errno));
14#ifdef __ANDROID__
15        return "Accessing \"/proc/stat\" is restricted on Android O+";
16#else
17        return "ffReadFileData(\"/proc/stat\", ARRAY_SIZE(buf) - 1, buf) failed";
18#endif
19    }
20    buf[nRead] = '\0';
21
22    // Skip first line
23    char* start = nullptr;
24    if ((start = strchr(buf, '\n')) == nullptr) {
25        FF_DEBUG("skip first line failed");
26        return "skip first line failed";
27    }
28    ++start;
29
30    uint64_t user = 0, nice = 0, system = 0, idle = 0, iowait = 0, irq = 0, softirq = 0;
31    char* token = nullptr;
32    while ((token = strchr(start, '\n'))) {
33        if (sscanf(start, "cpu%*d%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%*[^\n]\n", &user, &nice, &system, &idle, &iowait, &irq, &softirq) == 7) {
34            uint64_t inUse = user + nice + system + irq + softirq;
35            uint64_t total = inUse + idle + iowait;
36
37            FFCpuUsageInfo* info = FF_LIST_ADD(FFCpuUsageInfo, *cpuTimes);
38            *info = (FFCpuUsageInfo) {
39                .inUseAll = inUse,
40                .totalAll = total,
41            };
42        } else {
43            break;
44        }
45        start = token + 1;
46    }
47
48    return nullptr;
49}