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>
25 static int prev_total = 0;
26 static int prev_idle = 0;
29 * Reads the CPU utilization from /proc/stat and returns the usage as a
33 void print_cpu_usage(yajl_gen json_gen, char *buffer, const char *format) {
35 char *outwalk = buffer;
37 int curr_user = 0, curr_nice = 0, curr_system = 0, curr_idle = 0, curr_total;
38 int diff_idle, diff_total, diff_usage;
41 static char statpath[512];
42 strcpy(statpath, "/proc/stat");
43 if (!slurp(statpath, buf, sizeof(buf)) ||
44 sscanf(buf, "cpu %d %d %d %d", &curr_user, &curr_nice, &curr_system, &curr_idle) != 4)
47 curr_total = curr_user + curr_nice + curr_system + curr_idle;
48 diff_idle = curr_idle - prev_idle;
49 diff_total = curr_total - prev_total;
50 diff_usage = (diff_total ? (1000 * (diff_total - diff_idle)/diff_total + 5)/10 : 0);
51 prev_total = curr_total;
52 prev_idle = curr_idle;
53 #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
55 #if defined(__FreeBSD__) || defined(__DragonFly__)
57 long cp_time[CPUSTATES];
58 size = sizeof cp_time;
59 if (sysctlbyname("kern.cp_time", &cp_time, &size, NULL, 0) < 0)
62 /* This information is taken from the boot cpu, any other cpus are currently ignored. */
63 long cp_time[CPUSTATES];
65 size_t size = sizeof(cp_time);
70 if (sysctl(mib, 2, cp_time, &size, NULL, 0))
74 curr_user = cp_time[CP_USER];
75 curr_nice = cp_time[CP_NICE];
76 curr_system = cp_time[CP_SYS];
77 curr_idle = cp_time[CP_IDLE];
78 curr_total = curr_user + curr_nice + curr_system + curr_idle;
79 diff_idle = curr_idle - prev_idle;
80 diff_total = curr_total - prev_total;
81 diff_usage = (diff_total ? (1000 * (diff_total - diff_idle)/diff_total + 5)/10 : 0);
82 prev_total = curr_total;
83 prev_idle = curr_idle;
87 for (walk = format; *walk != '\0'; walk++) {
93 if (strncmp(walk+1, "usage", strlen("usage")) == 0) {
94 outwalk += sprintf(outwalk, "%02d%%", diff_usage);
95 walk += strlen("usage");
99 OUTPUT_FULL_TEXT(buffer);
102 OUTPUT_FULL_TEXT("cant read cpu usage");
103 (void)fputs("i3status: Cannot read CPU usage\n", stderr);