From 349da2b29fc57b5f29b6f2d4a04488b25fbf8ee7 Mon Sep 17 00:00:00 2001 From: Lukasz Stanislawski Date: Sun, 10 Jun 2018 23:27:43 +0200 Subject: [PATCH] procfs: implement cpu usage Change-Id: Ic740b533722f6b3646528295d76bb43a0c01ce37 --- src/procfs.c | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/procfs.c b/src/procfs.c index 90bf5e6..a7a461c 100644 --- a/src/procfs.c +++ b/src/procfs.c @@ -15,6 +15,7 @@ */ #include +#include #include "procfs.h" #include "log.h" @@ -24,6 +25,7 @@ #define UPTIME_FILEPATH "/proc/uptime" #define POSSIBLE_CPUS_FILEPATH "/sys/devices/system/cpu/possible" #define MEMINFO_FILEPATH "/proc/meminfo" +#define STAT_FILEPATH "/proc/stat" int procfs_read_system_load_average(struct procfs_load_average_info *info) { @@ -52,8 +54,33 @@ int procfs_read_system_load_average(struct procfs_load_average_info *info) return 0; } -int profcs_read_system_cpu_usage(struct procfs_system_cpu_usage_info *usage) +int procfs_read_system_cpu_usage(struct procfs_system_cpu_usage_info *usage) { + ON_NULL_RETURN_VAL(usage, -1); + + char line[256]; + struct procfs_system_cpu_usage_info tmp; + const char *prefix = "cpu "; + + FILE *stat_fp = fopen(STAT_FILEPATH, "r"); + if (!stat_fp) { + ERR("failed to open " STAT_FILEPATH); + return -1; + } + + while (fgets(line, sizeof(line), stat_fp)) { + if (!strncmp(line, prefix, strlen(prefix)) && + sscanf(line + 4, "%llu %llu %llu %llu %llu %llu %llu", + &tmp.user, &tmp.nice, &tmp.system, &tmp.idle, + &tmp.iowait, &tmp.irq, &tmp.softirq) == 7) { + *usage = tmp; + fclose(stat_fp); + return 0; + } + } + + fclose(stat_fp); + return -1; } -- 2.7.4