uloop: allow passing 0 as timeout to uloop_run
[project/libubox.git] / uloop.c
diff --git a/uloop.c b/uloop.c
index e60fb09..d2f41bb 100644 (file)
--- a/uloop.c
+++ b/uloop.c
@@ -58,10 +58,12 @@ static struct list_head processes = LIST_HEAD_INIT(processes);
 
 static int poll_fd = -1;
 bool uloop_cancelled = false;
+static int uloop_status = 0;
 static bool do_sigchld = false;
 
 static struct uloop_fd_event cur_fds[ULOOP_MAX_EVENTS];
 static int cur_fd, cur_nfds;
+static int uloop_run_depth = 0;
 
 int uloop_fd_add(struct uloop_fd *sock, unsigned int flags);
 
@@ -386,11 +388,18 @@ static void uloop_handle_processes(void)
 
 static void uloop_signal_wake(void)
 {
-       write(waker_pipe, "w", 1);
+       do {
+               if (write(waker_pipe, "w", 1) < 0) {
+                       if (errno == EINTR)
+                               continue;
+               }
+               break;
+       } while (1);
 }
 
 static void uloop_handle_sigint(int signo)
 {
+       uloop_status = signo;
        uloop_cancelled = true;
        uloop_signal_wake();
 }
@@ -506,20 +515,26 @@ static void uloop_clear_processes(void)
                uloop_process_delete(p);
 }
 
-void uloop_run(void)
+bool uloop_cancelling(void)
 {
-       static int recursive_calls = 0;
+       return uloop_run_depth > 0 && uloop_cancelled;
+}
+
+int uloop_run_timeout(int timeout)
+{
+       int next_time = 0;
        struct timeval tv;
 
        /*
         * Handlers are only updated for the first call to uloop_run() (and restored
         * when this call is done).
         */
-       if (!recursive_calls++)
+       if (!uloop_run_depth++)
                uloop_setup_signals(true);
 
+       uloop_status = 0;
        uloop_cancelled = false;
-       while(!uloop_cancelled)
+       while (!uloop_cancelled)
        {
                uloop_gettime(&tv);
                uloop_process_timeouts(&tv);
@@ -531,11 +546,17 @@ void uloop_run(void)
                        break;
 
                uloop_gettime(&tv);
-               uloop_run_events(uloop_get_next_timeout(&tv));
+
+               next_time = uloop_get_next_timeout(&tv);
+               if (timeout >= 0 && timeout < next_time)
+                       next_time = timeout;
+               uloop_run_events(next_time);
        }
 
-       if (!--recursive_calls)
+       if (!--uloop_run_depth)
                uloop_setup_signals(false);
+
+       return uloop_status;
 }
 
 void uloop_done(void)