uloop: allow specifying a timeout for uloop_run()
[project/libubox.git] / uloop.c
diff --git a/uloop.c b/uloop.c
index 1c5bcee..f503241 100644 (file)
--- a/uloop.c
+++ b/uloop.c
@@ -63,6 +63,7 @@ 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);
 
@@ -514,16 +515,21 @@ static void uloop_clear_processes(void)
                uloop_process_delete(p);
 }
 
-int 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;
@@ -540,10 +546,14 @@ int 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 && next_time < timeout)
+                       timeout = next_time;
+               uloop_run_events(timeout);
        }
 
-       if (!--recursive_calls)
+       if (!--uloop_run_depth)
                uloop_setup_signals(false);
 
        return uloop_status;