1 // vim:ts=4:sw=4: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 #if defined(__OpenBSD__)
14 #include <sys/sched.h>
16 #include <sys/dkstat.h>
20 #if defined(__DragonFly__)
21 #include <sys/param.h>
22 #include <sys/types.h>
23 #include <sys/sysctl.h>
24 #include <sys/resource.h>
27 #if defined(__NetBSD__)
28 #include <sys/param.h>
29 #include <sys/resource.h>
30 #include <sys/sysctl.h>
31 #include <sys/sched.h>
36 static int prev_total = 0;
37 static int prev_idle = 0;
40 * Reads the CPU utilization from /proc/stat and returns the usage as a
44 void print_cpu_usage(yajl_gen json_gen, char *buffer, const char *format) {
46 char *outwalk = buffer;
47 int curr_user = 0, curr_nice = 0, curr_system = 0, curr_idle = 0, curr_total;
48 int diff_idle, diff_total, diff_usage;
51 static char statpath[512];
53 strcpy(statpath, "/proc/stat");
54 if (!slurp(statpath, buf, sizeof(buf)) ||
55 sscanf(buf, "cpu %d %d %d %d", &curr_user, &curr_nice, &curr_system, &curr_idle) != 4)
58 curr_total = curr_user + curr_nice + curr_system + curr_idle;
59 diff_idle = curr_idle - prev_idle;
60 diff_total = curr_total - prev_total;
61 diff_usage = (diff_total ? (1000 * (diff_total - diff_idle) / diff_total + 5) / 10 : 0);
62 prev_total = curr_total;
63 prev_idle = curr_idle;
64 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
66 #if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__NetBSD__)
68 long cp_time[CPUSTATES];
69 size = sizeof cp_time;
70 if (sysctlbyname("kern.cp_time", &cp_time, &size, NULL, 0) < 0)
73 /* This information is taken from the boot cpu, any other cpus are currently ignored. */
74 long cp_time[CPUSTATES];
76 size_t size = sizeof(cp_time);
81 if (sysctl(mib, 2, cp_time, &size, NULL, 0))
85 curr_user = cp_time[CP_USER];
86 curr_nice = cp_time[CP_NICE];
87 curr_system = cp_time[CP_SYS];
88 curr_idle = cp_time[CP_IDLE];
89 curr_total = curr_user + curr_nice + curr_system + curr_idle;
90 diff_idle = curr_idle - prev_idle;
91 diff_total = curr_total - prev_total;
92 diff_usage = (diff_total ? (1000 * (diff_total - diff_idle) / diff_total + 5) / 10 : 0);
93 prev_total = curr_total;
94 prev_idle = curr_idle;
98 for (walk = format; *walk != '\0'; walk++) {
100 *(outwalk++) = *walk;
104 if (BEGINS_WITH(walk + 1, "usage")) {
105 outwalk += sprintf(outwalk, "%02d%%", diff_usage);
106 walk += strlen("usage");
110 OUTPUT_FULL_TEXT(buffer);
113 OUTPUT_FULL_TEXT("cant read cpu usage");
114 (void)fputs("i3status: Cannot read CPU usage\n", stderr);