Commit | Line | Data |
---|---|---|
55883d9a SK |
1 | #include <errno.h> |
2 | #include <fcntl.h> | |
3 | #include <stdio.h> | |
4 | #include <stdlib.h> | |
5 | #include <string.h> | |
6 | #include <unistd.h> | |
7 | ||
8 | #include "khatus_lib_log.h" | |
9 | #include "khatus_lib_sensor.h" | |
10 | #include "khatus_lib_time.h" | |
11 | ||
12 | void | |
fa2a9b44 SK |
13 | loop( |
14 | struct timespec *ti, | |
15 | char *fifo, | |
16 | char *buf, | |
17 | int fun(char *, void *), | |
18 | void *params) | |
55883d9a SK |
19 | { |
20 | int fd = -1; | |
21 | int w = -1; /* written */ | |
22 | int r = -1; /* remaining */ | |
23 | int i = -1; /* buffer position */ | |
24 | ||
25 | for (;;) { | |
26 | debug("openning \"%s\"\n", fifo); | |
27 | fd = open(fifo, O_WRONLY); | |
28 | if (fd < 0) | |
29 | fatal("Failed to open FIFO file: \"%s\". Error: %s\n", | |
30 | fifo, | |
31 | strerror(errno)); | |
32 | debug("openned. fd: %d\n", fd); | |
fa2a9b44 | 33 | r = fun(buf, params); |
55883d9a SK |
34 | buf[r] = END_OF_MESSAGE; |
35 | for (i = 0; (w = write(fd, buf + i++, 1)) && r; r--) | |
36 | ; | |
37 | if (w < 0) | |
38 | switch (errno) { | |
39 | case EPIPE: | |
40 | error("Broken pipe. Msg buf: %s\n", buf); | |
41 | break; | |
42 | default: | |
43 | fatal( | |
44 | "Failed to write to %s. " | |
45 | "Err num: %d, Err msg: %s\n", | |
46 | fifo, | |
47 | errno, | |
48 | strerror(errno)); | |
49 | } | |
50 | if (close(fd) < 0) | |
51 | fatal("Failed to close %s. Err num: %d, Err msg: %s\n", | |
52 | fifo, | |
53 | errno, | |
54 | strerror(errno)); | |
55 | fd = -1; | |
56 | debug("closed. fd: %d\n", fd); | |
57 | snooze(ti); | |
58 | } | |
59 | } |