1 // vim:sw=8:sts=8:ts=8:expandtab
6 #include <yajl/yajl_gen.h>
7 #include <yajl/yajl_version.h>
9 #if defined(__FreeBSD__) || defined(__OpenBSD__)
10 #include <sys/param.h>
11 #include <sys/types.h>
12 #include <sys/sysctl.h>
13 #include <sys/dkstat.h>
16 #if defined(__DragonFly__)
17 #include <sys/param.h>
18 #include <sys/types.h>
19 #include <sys/sysctl.h>
20 #include <sys/resource.h>
23 #if defined(__NetBSD__)
24 #include <sys/param.h>
25 #include <sys/resource.h>
26 #include <sys/sysctl.h>
27 #include <sys/sched.h>
32 static int prev_total = 0;
33 static int prev_idle = 0;
36 * Reads the CPU utilization from /proc/stat and returns the usage as a
40 void print_cpu_usage(yajl_gen json_gen, char *buffer, const char *format) {
42 char *outwalk = buffer;
44 int curr_user = 0, curr_nice = 0, curr_system = 0, curr_idle = 0, curr_total;
45 int diff_idle, diff_total, diff_usage;
48 static char statpath[512];
49 strcpy(statpath, "/proc/stat");
50 if (!slurp(statpath, buf, sizeof(buf)) ||
51 sscanf(buf, "cpu %d %d %d %d", &curr_user, &curr_nice, &curr_system, &curr_idle) != 4)
54 curr_total = curr_user + curr_nice + curr_system + curr_idle;
55 diff_idle = curr_idle - prev_idle;
56 diff_total = curr_total - prev_total;
57 diff_usage = (diff_total ? (1000 * (diff_total - diff_idle)/diff_total + 5)/10 : 0);
58 prev_total = curr_total;
59 prev_idle = curr_idle;
60 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
62 #if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__NetBSD__)
64 long cp_time[CPUSTATES];
65 size = sizeof cp_time;
66 if (sysctlbyname("kern.cp_time", &cp_time, &size, NULL, 0) < 0)
69 /* This information is taken from the boot cpu, any other cpus are currently ignored. */
70 long cp_time[CPUSTATES];
72 size_t size = sizeof(cp_time);
77 if (sysctl(mib, 2, cp_time, &size, NULL, 0))
81 curr_user = cp_time[CP_USER];
82 curr_nice = cp_time[CP_NICE];
83 curr_system = cp_time[CP_SYS];
84 curr_idle = cp_time[CP_IDLE];
85 curr_total = curr_user + curr_nice + curr_system + curr_idle;
86 diff_idle = curr_idle - prev_idle;
87 diff_total = curr_total - prev_total;
88 diff_usage = (diff_total ? (1000 * (diff_total - diff_idle)/diff_total + 5)/10 : 0);
89 prev_total = curr_total;
90 prev_idle = curr_idle;
94 for (walk = format; *walk != '\0'; walk++) {
100 if (strncmp(walk+1, "usage", strlen("usage")) == 0) {
101 outwalk += sprintf(outwalk, "%02d%%", diff_usage);
102 walk += strlen("usage");
106 OUTPUT_FULL_TEXT(buffer);
109 OUTPUT_FULL_TEXT("cant read cpu usage");
110 (void)fputs("i3status: Cannot read CPU usage\n", stderr);