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
103
104
105
106
107
108
109
110
111
|
#include "signal.h"
#include "text.h"
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#define SOMEBAR_CMD "status"
struct state {
int fd;
struct text * text;
};
static bool
file_exists(const char * path)
{
int fd = open(path, O_RDONLY);
bool exists = fd > 0;
if(exists) close(fd);
return exists;
}
static int
open_fifo(const char * path)
{
int rc;
if(!file_exists(path)) {
rc = mkfifo(path, 0644);
if(rc < 0) return -1;
}
return open(path, O_WRONLY);
}
static int
init_state(struct state * s)
{
char * dir = getenv("XDG_RUNTIME_DIR");
char * file = "/somebar-0";
size_t dir_len = strlen(dir);
size_t file_len = strlen(file);
size_t path_len = dir_len + file_len + 1;
char path[path_len];
memset(path, '\0', path_len);
strncat(path, dir, dir_len);
strncat(path, file, file_len);
s->text = NULL;
s->fd = open_fifo(path);
if(s->fd < 1) return -1;
s->text = text_new();
return 0;
}
static void
deinit_state(struct state * s)
{
if(s->fd > 0) close(s->fd);
if(s->text) text_free(s->text);
}
static void
update_status(struct state * s)
{
const size_t
cmd_len = strlen(SOMEBAR_CMD),
msg_len = TEXT_SIZE + cmd_len + 3;
size_t actual_len;
char msg[msg_len];
text_update(s->text);
snprintf(msg, msg_len, "%s %s\n", SOMEBAR_CMD, text_get_val(s->text));
actual_len = strlen(msg);
write(s->fd, msg, actual_len);
}
static void
run_loop(struct state * s)
{
while(signal_running) {
update_status(s);
usleep(1000 * 800);
}
}
int main(void)
{
int rc;
struct state s;
signal_setup_actions();
rc = init_state(&s);
if(rc == 0) run_loop(&s);
deinit_state(&s);
return 0;
}
|