procfs: implement cpu usage 71/181171/5
authorLukasz Stanislawski <lukasz.stanislawski@gmail.com>
Sun, 10 Jun 2018 21:27:43 +0000 (23:27 +0200)
committerLukasz Stanislawski <l.stanislaws@samsung.com>
Tue, 12 Jun 2018 10:09:17 +0000 (10:09 +0000)
Change-Id: Ic740b533722f6b3646528295d76bb43a0c01ce37

src/procfs.c

index 90bf5e6..a7a461c 100644 (file)
@@ -15,6 +15,7 @@
  */
 
 #include <stdio.h>
+#include <string.h>
 
 #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;
 }