]> git.sur5r.net Git - i3/i3status/blob - src/print_cpu_usage.c
Properly output JSON with libyajl
[i3/i3status] / src / print_cpu_usage.c
1 // vim:sw=8:sts=8:ts=8:expandtab
2 #include <stdlib.h>
3 #include <limits.h>
4 #include <stdio.h>
5 #include <string.h>
6 #include <yajl/yajl_gen.h>
7
8 #ifdef __FreeBSD__
9 #include <sys/types.h>
10 #include <sys/sysctl.h>
11 #include <sys/dkstat.h>
12 #endif
13
14 #include "i3status.h"
15
16 static int prev_total = 0;
17 static int prev_idle  = 0;
18
19 /*
20  * Reads the CPU utilization from /proc/stat and returns the usage as a
21  * percentage.
22  *
23  */
24 void print_cpu_usage(yajl_gen json_gen, char *buffer, const char *format) {
25         const char *walk;
26         char *outwalk = buffer;
27         char buf[1024];
28         int curr_user = 0, curr_nice = 0, curr_system = 0, curr_idle = 0, curr_total;
29         int diff_idle, diff_total, diff_usage;
30
31 #if defined(LINUX)
32         static char statpath[512];
33         strcpy(statpath, "/proc/stat");
34         if (!slurp(statpath, buf, sizeof(buf)) ||
35             sscanf(buf, "cpu %d %d %d %d", &curr_user, &curr_nice, &curr_system, &curr_idle) != 4)
36                 goto error;
37
38         curr_total = curr_user + curr_nice + curr_system + curr_idle;
39         diff_idle  = curr_idle - prev_idle;
40         diff_total = curr_total - prev_total;
41         diff_usage = (1000 * (diff_total - diff_idle)/diff_total + 5)/10;
42         prev_total = curr_total;
43         prev_idle  = curr_idle;
44 #elif defined(__FreeBSD__)
45         size_t size;
46         long cp_time[CPUSTATES];
47         size = sizeof cp_time;
48         if (sysctlbyname("kern.cp_time", &cp_time, &size, NULL, 0) < 0)
49                 goto error;
50
51         curr_user = cp_time[CP_USER];
52         curr_nice = cp_time[CP_NICE];
53         curr_system = cp_time[CP_SYS];
54         curr_idle = cp_time[CP_IDLE];
55         curr_total = curr_user + curr_nice + curr_system + curr_idle;
56         diff_idle  = curr_idle - prev_idle;
57         diff_total = curr_total - prev_total;
58         diff_usage = (1000 * (diff_total - diff_idle)/diff_total + 5)/10;
59         prev_total = curr_total;
60         prev_idle  = curr_idle;
61 #else
62         goto error;
63 #endif
64         for (walk = format; *walk != '\0'; walk++) {
65                 if (*walk != '%') {
66                         *(outwalk++) = *walk;
67                         continue;
68                 }
69
70                 if (strncmp(walk+1, "usage", strlen("usage")) == 0) {
71                         outwalk += sprintf(outwalk, "%02d%%", diff_usage);
72                         walk += strlen("usage");
73                 }
74         }
75
76         OUTPUT_FULL_TEXT(buffer);
77         return;
78 error:
79         (void)fputs("Cannot read usage\n", stderr);
80 }