]> git.itanic.dy.fi Git - log-plotter/blob - main.c
main: Open ouput file when one is requested
[log-plotter] / main.c
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <fcntl.h>
4 #include <sys/epoll.h>
5 #include <sys/types.h>
6 #include <sys/stat.h>
7
8 #include "options.h"
9 #include "baud.h"
10 #include "debug.h"
11
12 int main(int argc, char *argv[])
13 {
14         struct epoll_event ev;
15         struct plotter_options options;
16         int fd, baud, ret, out_fd = STDOUT_FILENO;
17         int epoll_fd;
18         char buf[256];
19
20
21         if (read_args(argc, argv, &options))
22                 return 1;
23
24         baud = options.baud_rate;
25         fd = open_at_baud(options.device_path, &baud);
26         if (fd < 0)
27                 return 1;
28
29         if (baud != options.baud_rate) {
30                 pr_err("Failed to set baudrate to %d, only got %d\n",
31                         options.baud_rate, baud);
32                 ret = 1;
33                 goto out;
34         }
35
36         if (options.output_path) {
37                 pr_debug("Opening %s for writing the log file\n",
38                         options.output_path);
39
40                 out_fd = open(options.output_path,
41                         O_CREAT | O_APPEND | O_WRONLY, 0664);
42                 if (out_fd < 0) {
43                         pr_err("Failed to open file %s for writing: %m\n",
44                                 options.output_path);
45                         ret = 1;
46                         goto out;
47                 }
48         }
49
50         epoll_fd = epoll_create(1);
51
52         ev.events = EPOLLIN;
53         ev.data.fd = fd;
54         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
55                 pr_err("epoll_ctl: %m\n");
56                 return 1;
57         }
58
59         while (1) {
60                 ret = epoll_wait(epoll_fd, &ev, 1, -1);
61                 if (ret == 0)
62                         continue;
63
64                 if (ret < 0) {
65                         pr_err("epoll: %m\n");
66                         return 1;
67                 }
68
69                 ret = read(fd, buf, sizeof(buf));
70                 if (read < 0) {
71                         pr_err("read: %m\n");
72                         break;
73                 }
74
75                 if (ret == 0) {
76                         pr_err("Read EOF, stopping\n");
77                         break;
78                 }
79
80                 ret = write(1, buf, ret);
81                 if (read < 0) {
82                         pr_err("write: %m\n");
83                         break;
84                 }
85         }
86
87 out:
88         close(fd);
89         return ret;
90 }