1 // vim:sw=8:sts=8:ts=8:expandtab
6 #include <yajl/yajl_gen.h>
7 #include <yajl/yajl_version.h>
10 #include <sys/types.h>
11 #include <sys/sysctl.h>
12 #include <sys/dkstat.h>
17 static int prev_total = 0;
18 static int prev_idle = 0;
21 * Reads the CPU utilization from /proc/stat and returns the usage as a
25 void print_cpu_usage(yajl_gen json_gen, char *buffer, const char *format) {
27 char *outwalk = buffer;
29 int curr_user = 0, curr_nice = 0, curr_system = 0, curr_idle = 0, curr_total;
30 int diff_idle, diff_total, diff_usage;
33 static char statpath[512];
34 strcpy(statpath, "/proc/stat");
35 if (!slurp(statpath, buf, sizeof(buf)) ||
36 sscanf(buf, "cpu %d %d %d %d", &curr_user, &curr_nice, &curr_system, &curr_idle) != 4)
39 curr_total = curr_user + curr_nice + curr_system + curr_idle;
40 diff_idle = curr_idle - prev_idle;
41 diff_total = curr_total - prev_total;
42 diff_usage = (1000 * (diff_total - diff_idle)/diff_total + 5)/10;
43 prev_total = curr_total;
44 prev_idle = curr_idle;
45 #elif defined(__FreeBSD__)
47 long cp_time[CPUSTATES];
48 size = sizeof cp_time;
49 if (sysctlbyname("kern.cp_time", &cp_time, &size, NULL, 0) < 0)
52 curr_user = cp_time[CP_USER];
53 curr_nice = cp_time[CP_NICE];
54 curr_system = cp_time[CP_SYS];
55 curr_idle = cp_time[CP_IDLE];
56 curr_total = curr_user + curr_nice + curr_system + curr_idle;
57 diff_idle = curr_idle - prev_idle;
58 diff_total = curr_total - prev_total;
59 diff_usage = (1000 * (diff_total - diff_idle)/diff_total + 5)/10;
60 prev_total = curr_total;
61 prev_idle = curr_idle;
65 for (walk = format; *walk != '\0'; walk++) {
71 if (strncmp(walk+1, "usage", strlen("usage")) == 0) {
72 outwalk += sprintf(outwalk, "%02d%%", diff_usage);
73 walk += strlen("usage");
77 OUTPUT_FULL_TEXT(buffer);
80 (void)fputs("Cannot read usage\n", stderr);