change minimum cmake version to 2.6
[project/libubox.git] / uloop.c
diff --git a/uloop.c b/uloop.c
index ec37925..f60eb41 100644 (file)
--- a/uloop.c
+++ b/uloop.c
 #endif
 #define ULOOP_MAX_EVENTS 10
 
-struct uloop_timeout *first_timeout;
-static int poll_fd;
-static bool cancel;
+static struct uloop_timeout *first_timeout;
+static int poll_fd = -1;
+bool uloop_cancelled = false;
 
 #ifdef USE_KQUEUE
 
 int uloop_init(void)
 {
+       if (poll_fd >= 0)
+               return 0;
+
        poll_fd = kqueue();
        if (poll_fd < 0)
                return -1;
@@ -94,7 +97,7 @@ static int register_poll(struct uloop_fd *fd, unsigned int flags)
 
        if (changed & ULOOP_WRITE) {
                uint16_t kflags = get_flags(flags, ULOOP_WRITE);
-               EV_SET(&ev[nev++], fd->fd, EVFILT_READ, kflags, 0, 0, fd);
+               EV_SET(&ev[nev++], fd->fd, EVFILT_WRITE, kflags, 0, 0, fd);
        }
 
        if (nev && (kevent(poll_fd, ev, nev, NULL, 0, &timeout) == -1))
@@ -118,7 +121,7 @@ static void uloop_run_events(int timeout)
 
        if (timeout > 0) {
                ts.tv_sec = timeout / 1000;
-               ts.tv_nsec = timeout * 1000000;
+               ts.tv_nsec = (timeout % 1000) * 1000000;
        }
 
        nfds = kevent(poll_fd, NULL, 0, events, ARRAY_SIZE(events), timeout > 0 ? &ts : NULL);
@@ -160,6 +163,9 @@ static void uloop_run_events(int timeout)
 
 int uloop_init(void)
 {
+       if (poll_fd >= 0)
+               return 0;
+
        poll_fd = epoll_create(32);
        if (poll_fd < 0)
                return -1;
@@ -236,7 +242,7 @@ int uloop_fd_add(struct uloop_fd *sock, unsigned int flags)
        unsigned int fl;
        int ret;
 
-       if (!sock->registered) {
+       if (!sock->registered && !(flags & ULOOP_BLOCKING)) {
                fl = fcntl(sock->fd, F_GETFL, 0);
                fl |= O_NONBLOCK;
                fcntl(sock->fd, F_SETFL, fl);
@@ -327,7 +333,7 @@ int uloop_timeout_cancel(struct uloop_timeout *timeout)
 
 static void uloop_handle_sigint(int signo)
 {
-       cancel = true;
+       uloop_cancelled = true;
 }
 
 static void uloop_setup_signals(void)
@@ -368,25 +374,26 @@ static void uloop_process_timeouts(struct timeval *tv)
        }
 }
 
-void uloop_end(void)
-{
-       cancel = true;
-}
-
 void uloop_run(void)
 {
        struct timeval tv;
 
        uloop_setup_signals();
-       while(!cancel)
+       while(!uloop_cancelled)
        {
                gettimeofday(&tv, NULL);
                uloop_process_timeouts(&tv);
+               if (uloop_cancelled)
+                       break;
                uloop_run_events(uloop_get_next_timeout(&tv));
        }
 }
 
 void uloop_done(void)
 {
+       if (poll_fd < 0)
+               return;
+
        close(poll_fd);
+       poll_fd = -1;
 }