]> git.sur5r.net Git - i3/i3status/blob - src/print_load.c
Error handling: Never output null as full_text (JSON), prefix messages with i3status...
[i3/i3status] / src / print_load.c
1 // vim:ts=8:expandtab
2 #include "i3status.h"
3 #include <stdlib.h>
4 #include <stdio.h>
5 #include <string.h>
6 #include <yajl/yajl_gen.h>
7 #include <yajl/yajl_version.h>
8
9 void print_load(yajl_gen json_gen, char *buffer, const char *format) {
10         char *outwalk = buffer;
11         /* Get load */
12
13 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(linux) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) || defined(sun)
14         double loadavg[3];
15         const char *walk;
16
17         if (getloadavg(loadavg, 3) == -1)
18                 goto error;
19
20         for (walk = format; *walk != '\0'; walk++) {
21                 if (*walk != '%') {
22                         *(outwalk++) = *walk;
23                         continue;
24                 }
25
26                 if (BEGINS_WITH(walk+1, "1min")) {
27                         outwalk += sprintf(outwalk, "%1.2f", loadavg[0]);
28                         walk += strlen("1min");
29                 }
30
31                 if (BEGINS_WITH(walk+1, "5min")) {
32                         outwalk += sprintf(outwalk, "%1.2f", loadavg[1]);
33                         walk += strlen("5min");
34                 }
35
36                 if (BEGINS_WITH(walk+1, "15min")) {
37                         outwalk += sprintf(outwalk, "%1.2f", loadavg[2]);
38                         walk += strlen("15min");
39                 }
40         }
41
42         *outwalk = '\0';
43         OUTPUT_FULL_TEXT(buffer);
44
45         return;
46 error:
47 #endif
48         OUTPUT_FULL_TEXT("cant read load");
49         (void)fputs("i3status: Cannot read system load using getloadavg()\n", stderr);
50 }