From 564f4d9d9c2cc16e53265c40ad63712cf14f534d Mon Sep 17 00:00:00 2001 From: Timo Kokkonen Date: Sun, 6 Oct 2013 21:39:45 +0300 Subject: [PATCH] main: Refactor data reading out from main Keep the main function simple. Factor out all irrelevant data processing. Signed-off-by: Timo Kokkonen --- main.c | 88 +++++++++++++++++++++++++++++++++------------------------- 1 file changed, 50 insertions(+), 38 deletions(-) diff --git a/main.c b/main.c index 9ac44f9..6189b7b 100644 --- a/main.c +++ b/main.c @@ -9,49 +9,22 @@ #include "baud.h" #include "debug.h" -int main(int argc, char *argv[]) +int read_data(int infd, int outfd) { struct epoll_event ev; - struct plotter_options options; - int fd, baud, ret, out_fd = STDOUT_FILENO; int epoll_fd; + int ret; char buf[256]; - - if (read_args(argc, argv, &options)) - return 1; - - baud = options.baud_rate; - fd = open_at_baud(options.device_path, &baud); - if (fd < 0) - return 1; - - if (baud != options.baud_rate) { - pr_err("Failed to set baudrate to %d, only got %d\n", - options.baud_rate, baud); - ret = 1; - goto out; - } - - if (options.output_path) { - pr_debug("Opening %s for writing the log file\n", - options.output_path); - - out_fd = open(options.output_path, - O_CREAT | O_APPEND | O_WRONLY, 0664); - if (out_fd < 0) { - pr_err("Failed to open file %s for writing: %m\n", - options.output_path); - ret = 1; - goto out; - } - } - epoll_fd = epoll_create(1); + if (epoll_fd < 0) { + pr_err("Failed to create epoll socket: %m\n"); + return -1; + } ev.events = EPOLLIN; - ev.data.fd = fd; - if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) { + ev.data.fd = infd; + if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, infd, &ev) == -1) { pr_err("epoll_ctl: %m\n"); return 1; } @@ -63,10 +36,10 @@ int main(int argc, char *argv[]) if (ret < 0) { pr_err("epoll: %m\n"); - return 1; + return -1; } - ret = read(fd, buf, sizeof(buf)); + ret = read(infd, buf, sizeof(buf)); if (read < 0) { pr_err("read: %m\n"); break; @@ -77,13 +50,52 @@ int main(int argc, char *argv[]) break; } - ret = write(1, buf, ret); + ret = write(outfd, buf, ret); if (read < 0) { pr_err("write: %m\n"); break; } } + return 0; +} + +int main(int argc, char *argv[]) +{ + struct plotter_options options; + int fd, baud, ret = 0, out_fd = STDOUT_FILENO; + + if (read_args(argc, argv, &options)) + return 1; + + baud = options.baud_rate; + fd = open_at_baud(options.device_path, &baud); + if (fd < 0) + return 1; + + if (baud != options.baud_rate) { + pr_err("Failed to set baudrate to %d, only got %d\n", + options.baud_rate, baud); + ret = 1; + goto out; + } + + if (options.output_path) { + pr_debug("Opening %s for writing the log file\n", + options.output_path); + + out_fd = open(options.output_path, + O_CREAT | O_APPEND | O_WRONLY, 0664); + if (out_fd < 0) { + pr_err("Failed to open file %s for writing: %m\n", + options.output_path); + ret = 1; + goto out; + } + } + + read_data(fd, out_fd); + out: close(fd); return ret; -- 2.44.0