]> git.itanic.dy.fi Git - log-plotter/commitdiff
main: Fix busy loop with reading
authorTimo Kokkonen <timo.t.kokkonen@iki.fi>
Mon, 30 Sep 2013 18:09:07 +0000 (21:09 +0300)
committerTimo Kokkonen <timo.t.kokkonen@iki.fi>
Mon, 30 Sep 2013 18:09:07 +0000 (21:09 +0300)
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 <timo.t.kokkonen@iki.fi>
main.c

diff --git a/main.c b/main.c
index b4a4c8fb635b2f813e23f4e6a43a403ae12abbdd..847a110c3bdbf2932609b8e8e8e3f4c149670166 100644 (file)
--- a/main.c
+++ b/main.c
@@ -1,11 +1,14 @@
 #include <stdio.h>
 #include <unistd.h>
+#include <sys/epoll.h>
 
 #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");