1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
|
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/inotify.h>
#include <poll.h>
#include <unistd.h>
#include <pthread.h>
#include <libudev.h>
static const char MONTHS[12][4] = {"Jan\0", "Feb\0", "Mar\0",
"Apr\0", "May\0", "Jun\0",
"Jul\0", "Aug\0", "Sep\0",
"Oct\0", "Nov\0", "Dec\0"
};
static const char DAYS[7][4] = {"Sun\0", "Mon\0", "Tue\0", "Wed\0", "Thu\0", "Fri\0", "Sat\0"};
static const char PM[2][3] = {"AM\0", "PM\0"};
static const char TLPS[3][4] = {"\0", "\0","\0"};
struct sb26 {
char *date;
unsigned char tlp_status;
unsigned short mem_used;
};
void *watchers(void *arg)
{
struct sb26 *sb = (struct sb26*)arg;
FILE *tlpf = fopen("/run/tlp/last_pwr", "r");
int inf = inotify_init();
int tlpw = inotify_add_watch(inf, "/run/tlp/last_pwr", IN_MODIFY);
ssize_t ev_s = sizeof(struct inotify_event) + NAME_MAX + 1;
struct pollfd pfd = {inf, POLLIN, 0};
struct inotify_event ev;
for (;;) {
fscanf(tlpf, "%hhu", &sb->tlp_status);
fseek(tlpf, 0, SEEK_SET);
poll(&pfd, 1, INT_MAX);
read(inf, (void *)&ev, ev_s);
if (ev.wd == tlpw) {
// TODO Handle other inotify watches
}
}
return NULL;
}
void tmfmt(char *tmf)
{
struct tm tm_s;
time_t tm = time(NULL);
tzset();
localtime_r(&tm, &tm_s);
unsigned char hr = tm_s.tm_hour % 12;
if (hr == 0) hr = 12;
snprintf(tmf, 21, "%s %s %02d %02d:%02d %s", DAYS[tm_s.tm_wday], MONTHS[tm_s.tm_mon], tm_s.tm_mday, hr, tm_s.tm_min, PM[tm_s.tm_hour/12]);
}
void *watch_mem(void *arg)
{
struct sb26 *sb = (struct sb26*)arg;
long total, avail;
char buf[25];
FILE *memf = fopen("/proc/meminfo", "r");
for (;;) {
fgets(buf, 25, memf);
/* strtol can handle arbitrary leading whitespace */
total = strtol((buf + 15), NULL, 10);
fseek(memf, 32, SEEK_CUR);
fgets(buf, 25, memf);
avail = strtol((buf + 15), NULL, 10);
unsigned int used = total - avail;
sb->mem_used = used >> 10;
fseek(memf, 0, SEEK_SET);
}
fclose(memf);
}
int main()
{
char tmf[21];
struct sb26 sb = { NULL, 0 };
pthread_t watcher;
pthread_create(&watcher, NULL, &watchers, (void *) &sb);
pthread_t mem;
pthread_create(&mem, NULL, &watch_mem , (void *) &sb);
while (1) {
tmfmt(tmf);
printf("%d mB %s %s\n", sb.mem_used, tmf, TLPS[sb.tlp_status]);
sleep(1);
}
pthread_join(watcher, NULL);
return 0;
}
|