From: Timo Kokkonen Date: Mon, 30 Sep 2013 18:09:07 +0000 (+0300) Subject: main: Fix busy loop with reading X-Git-Url: http://git.itanic.dy.fi/?p=log-plotter;a=commitdiff_plain;h=9719680d66d26ab962426dc75672f0f9d049ba18 main: Fix busy loop with reading As the baud.c opens the serial device with O_NBLOCK flag, read will just return immediately when there is nothing to read. That basically makes the read loop a a busy loop, consuming one CPU core fully at all times. Fix the problem by using epoll to wait until something becomes available on the serial port to read. Signed-off-by: Timo Kokkonen --- diff --git a/main.c b/main.c index b4a4c8f..847a110 100644 --- a/main.c +++ b/main.c @@ -1,11 +1,14 @@ #include #include +#include #include "baud.h" int main(int argc, char *argv[]) { + struct epoll_event ev; int fd, baud, ret; + int epoll_fd; char *device; char buf[256]; @@ -27,16 +30,31 @@ int main(int argc, char *argv[]) return 1; } + epoll_fd = epoll_create(1); + + ev.events = EPOLLIN; + ev.data.fd = fd; + if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) { + perror("epoll_ctl"); + return 1; + } + while (1) { + ret = epoll_wait(epoll_fd, &ev, 1, -1); + if (ret == 0) + continue; + + if (ret < 0) { + perror("epoll"); + return 1; + } + ret = read(fd, buf, sizeof(buf)); if (read < 0) { perror("read"); break; } - if (read == 0) - break; - ret = write(1, buf, ret); if (read < 0) { perror("write");