2 * libev event processing core, watcher management
4 * Copyright (c) 2007 Marc Alexander Lehmann <libev@schmorp.de>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions are
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * * Redistributions in binary form must reproduce the above
15 * copyright notice, this list of conditions and the following
16 * disclaimer in the documentation and/or other materials provided
17 * with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 # if HAVE_CLOCK_GETTIME
40 # ifndef EV_USE_MONOTONIC
41 # define EV_USE_MONOTONIC 1
43 # ifndef EV_USE_REALTIME
44 # define EV_USE_REALTIME 1
47 # ifndef EV_USE_MONOTONIC
48 # define EV_USE_MONOTONIC 0
50 # ifndef EV_USE_REALTIME
51 # define EV_USE_REALTIME 0
55 # ifndef EV_USE_SELECT
56 # if HAVE_SELECT && HAVE_SYS_SELECT_H
57 # define EV_USE_SELECT 1
59 # define EV_USE_SELECT 0
64 # if HAVE_POLL && HAVE_POLL_H
65 # define EV_USE_POLL 1
67 # define EV_USE_POLL 0
72 # if HAVE_EPOLL_CTL && HAVE_SYS_EPOLL_H
73 # define EV_USE_EPOLL 1
75 # define EV_USE_EPOLL 0
79 # ifndef EV_USE_KQUEUE
80 # if HAVE_KQUEUE && HAVE_SYS_EVENT_H && HAVE_SYS_QUEUE_H
81 # define EV_USE_KQUEUE 1
83 # define EV_USE_KQUEUE 0
88 # if HAVE_PORT_H && HAVE_PORT_CREATE
89 # define EV_USE_PORT 1
91 # define EV_USE_PORT 0
106 #include <sys/types.h>
113 # include <sys/time.h>
114 # include <sys/wait.h>
116 # define WIN32_LEAN_AND_MEAN
117 # include <windows.h>
118 # ifndef EV_SELECT_IS_WINSOCKET
119 # define EV_SELECT_IS_WINSOCKET 1
125 #ifndef EV_USE_MONOTONIC
126 # define EV_USE_MONOTONIC 0
129 #ifndef EV_USE_REALTIME
130 # define EV_USE_REALTIME 0
133 #ifndef EV_USE_SELECT
134 # define EV_USE_SELECT 1
139 # define EV_USE_POLL 0
141 # define EV_USE_POLL 1
146 # define EV_USE_EPOLL 0
149 #ifndef EV_USE_KQUEUE
150 # define EV_USE_KQUEUE 0
154 # define EV_USE_PORT 0
159 /* darwin simply cannot be helped */
162 # undef EV_USE_KQUEUE
165 #ifndef CLOCK_MONOTONIC
166 # undef EV_USE_MONOTONIC
167 # define EV_USE_MONOTONIC 0
170 #ifndef CLOCK_REALTIME
171 # undef EV_USE_REALTIME
172 # define EV_USE_REALTIME 0
175 #if EV_SELECT_IS_WINSOCKET
176 # include <winsock.h>
181 #define MIN_TIMEJUMP 1. /* minimum timejump that gets detected (if monotonic clock available) */
182 #define MAX_BLOCKTIME 59.743 /* never wait longer than this time (to detect time jumps) */
183 #define PID_HASHSIZE 16 /* size of pid hash table, must be power of two */
184 /*#define CLEANUP_INTERVAL (MAX_BLOCKTIME * 5.) /* how often to try to free memory and re-check fds */
193 # define expect(expr,value) __builtin_expect ((expr),(value))
194 # define inline static inline
196 # define expect(expr,value) (expr)
197 # define inline static
200 #define expect_false(expr) expect ((expr) != 0, 0)
201 #define expect_true(expr) expect ((expr) != 0, 1)
203 #define NUMPRI (EV_MAXPRI - EV_MINPRI + 1)
204 #define ABSPRI(w) ((w)->priority - EV_MINPRI)
206 #define EMPTY0 /* required for microsofts broken pseudo-c compiler */
207 #define EMPTY2(a,b) /* used to suppress some warnings */
209 typedef struct ev_watcher *W;
210 typedef struct ev_watcher_list *WL;
211 typedef struct ev_watcher_time *WT;
213 static int have_monotonic; /* did clock_gettime (CLOCK_MONOTONIC) work? */
216 # include "ev_win32.c"
219 /*****************************************************************************/
221 static void (*syserr_cb)(const char *msg);
223 void ev_set_syserr_cb (void (*cb)(const char *msg))
229 syserr (const char *msg)
232 msg = "(libev) system error";
243 static void *(*alloc)(void *ptr, long size);
245 void ev_set_allocator (void *(*cb)(void *ptr, long size))
251 ev_realloc (void *ptr, long size)
253 ptr = alloc ? alloc (ptr, size) : realloc (ptr, size);
257 fprintf (stderr, "libev: cannot allocate %ld bytes, aborting.", size);
264 #define ev_malloc(size) ev_realloc (0, (size))
265 #define ev_free(ptr) ev_realloc ((ptr), 0)
267 /*****************************************************************************/
272 unsigned char events;
274 #if EV_SELECT_IS_WINSOCKET
290 #define ev_rt_now ((loop)->ev_rt_now)
291 #define VAR(name,decl) decl;
297 static struct ev_loop default_loop_struct;
298 struct ev_loop *ev_default_loop_ptr;
303 #define VAR(name,decl) static decl;
307 static int ev_default_loop_ptr;
311 /*****************************************************************************/
318 clock_gettime (CLOCK_REALTIME, &ts);
319 return ts.tv_sec + ts.tv_nsec * 1e-9;
322 gettimeofday (&tv, 0);
323 return tv.tv_sec + tv.tv_usec * 1e-6;
331 if (expect_true (have_monotonic))
334 clock_gettime (CLOCK_MONOTONIC, &ts);
335 return ts.tv_sec + ts.tv_nsec * 1e-9;
350 #define array_roundsize(type,n) (((n) | 4) & ~3)
352 #define array_needsize(type,base,cur,cnt,init) \
353 if (expect_false ((cnt) > cur)) \
358 newcnt = array_roundsize (type, newcnt << 1); \
360 while ((cnt) > newcnt); \
362 base = (type *)ev_realloc (base, sizeof (type) * (newcnt));\
363 init (base + cur, newcnt - cur); \
367 #define array_slim(type,stem) \
368 if (stem ## max < array_roundsize (stem ## cnt >> 2)) \
370 stem ## max = array_roundsize (stem ## cnt >> 1); \
371 base = (type *)ev_realloc (base, sizeof (type) * (stem ## max));\
372 fprintf (stderr, "slimmed down " # stem " to %d\n", stem ## max);/*D*/\
375 #define array_free(stem, idx) \
376 ev_free (stem ## s idx); stem ## cnt idx = stem ## max idx = 0;
378 /*****************************************************************************/
381 anfds_init (ANFD *base, int count)
386 base->events = EV_NONE;
394 ev_feed_event (EV_P_ void *w, int revents)
398 if (expect_false (w_->pending))
400 pendings [ABSPRI (w_)][w_->pending - 1].events |= revents;
404 w_->pending = ++pendingcnt [ABSPRI (w_)];
405 array_needsize (ANPENDING, pendings [ABSPRI (w_)], pendingmax [ABSPRI (w_)], pendingcnt [ABSPRI (w_)], EMPTY2);
406 pendings [ABSPRI (w_)][w_->pending - 1].w = w_;
407 pendings [ABSPRI (w_)][w_->pending - 1].events = revents;
411 queue_events (EV_P_ W *events, int eventcnt, int type)
415 for (i = 0; i < eventcnt; ++i)
416 ev_feed_event (EV_A_ events [i], type);
420 fd_event (EV_P_ int fd, int revents)
422 ANFD *anfd = anfds + fd;
425 for (w = (struct ev_io *)anfd->head; w; w = (struct ev_io *)((WL)w)->next)
427 int ev = w->events & revents;
430 ev_feed_event (EV_A_ (W)w, ev);
435 ev_feed_fd_event (EV_P_ int fd, int revents)
437 fd_event (EV_A_ fd, revents);
440 /*****************************************************************************/
447 for (i = 0; i < fdchangecnt; ++i)
449 int fd = fdchanges [i];
450 ANFD *anfd = anfds + fd;
455 for (w = (struct ev_io *)anfd->head; w; w = (struct ev_io *)((WL)w)->next)
458 #if EV_SELECT_IS_WINSOCKET
462 anfd->handle = _get_osfhandle (fd);
463 assert (("libev only supports socket fds in this configuration", ioctlsocket (anfd->handle, FIONREAD, &argp) == 0));
469 method_modify (EV_A_ fd, anfd->events, events);
470 anfd->events = events;
477 fd_change (EV_P_ int fd)
479 if (expect_false (anfds [fd].reify))
482 anfds [fd].reify = 1;
485 array_needsize (int, fdchanges, fdchangemax, fdchangecnt, EMPTY2);
486 fdchanges [fdchangecnt - 1] = fd;
490 fd_kill (EV_P_ int fd)
494 while ((w = (struct ev_io *)anfds [fd].head))
496 ev_io_stop (EV_A_ w);
497 ev_feed_event (EV_A_ (W)w, EV_ERROR | EV_READ | EV_WRITE);
505 return _get_osfhandle (fd) != -1;
507 return fcntl (fd, F_GETFD) != -1;
511 /* called on EBADF to verify fds */
517 for (fd = 0; fd < anfdmax; ++fd)
518 if (anfds [fd].events)
519 if (!fd_valid (fd) == -1 && errno == EBADF)
523 /* called on ENOMEM in select/poll to kill some fds and retry */
529 for (fd = anfdmax; fd--; )
530 if (anfds [fd].events)
537 /* usually called after fork if method needs to re-arm all fds from scratch */
543 /* this should be highly optimised to not do anything but set a flag */
544 for (fd = 0; fd < anfdmax; ++fd)
545 if (anfds [fd].events)
547 anfds [fd].events = 0;
548 fd_change (EV_A_ fd);
552 /*****************************************************************************/
555 upheap (WT *heap, int k)
559 while (k && heap [k >> 1]->at > w->at)
561 heap [k] = heap [k >> 1];
562 ((W)heap [k])->active = k + 1;
567 ((W)heap [k])->active = k + 1;
572 downheap (WT *heap, int N, int k)
580 if (j + 1 < N && heap [j]->at > heap [j + 1]->at)
583 if (w->at <= heap [j]->at)
587 ((W)heap [k])->active = k + 1;
592 ((W)heap [k])->active = k + 1;
596 adjustheap (WT *heap, int N, int k)
599 downheap (heap, N, k);
602 /*****************************************************************************/
607 sig_atomic_t volatile gotsig;
610 static ANSIG *signals;
611 static int signalmax;
613 static int sigpipe [2];
614 static sig_atomic_t volatile gotsig;
615 static struct ev_io sigev;
618 signals_init (ANSIG *base, int count)
630 sighandler (int signum)
633 signal (signum, sighandler);
636 signals [signum - 1].gotsig = 1;
640 int old_errno = errno;
642 write (sigpipe [1], &signum, 1);
648 ev_feed_signal_event (EV_P_ int signum)
653 assert (("feeding signal events is only supported in the default loop", loop == ev_default_loop_ptr));
658 if (signum < 0 || signum >= signalmax)
661 signals [signum].gotsig = 0;
663 for (w = signals [signum].head; w; w = w->next)
664 ev_feed_event (EV_A_ (W)w, EV_SIGNAL);
668 sigcb (EV_P_ struct ev_io *iow, int revents)
672 read (sigpipe [0], &revents, 1);
675 for (signum = signalmax; signum--; )
676 if (signals [signum].gotsig)
677 ev_feed_signal_event (EV_A_ signum + 1);
685 ioctlsocket (_get_osfhandle (fd), FIONBIO, &arg);
687 fcntl (fd, F_SETFD, FD_CLOEXEC);
688 fcntl (fd, F_SETFL, O_NONBLOCK);
695 fd_intern (sigpipe [0]);
696 fd_intern (sigpipe [1]);
698 ev_io_set (&sigev, sigpipe [0], EV_READ);
699 ev_io_start (EV_A_ &sigev);
700 ev_unref (EV_A); /* child watcher should not keep loop alive */
703 /*****************************************************************************/
705 static struct ev_child *childs [PID_HASHSIZE];
709 static struct ev_signal childev;
712 # define WCONTINUED 0
716 child_reap (EV_P_ struct ev_signal *sw, int chain, int pid, int status)
720 for (w = (struct ev_child *)childs [chain & (PID_HASHSIZE - 1)]; w; w = (struct ev_child *)((WL)w)->next)
721 if (w->pid == pid || !w->pid)
723 ev_priority (w) = ev_priority (sw); /* need to do it *now* */
726 ev_feed_event (EV_A_ (W)w, EV_CHILD);
731 childcb (EV_P_ struct ev_signal *sw, int revents)
735 if (0 < (pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED)))
737 /* make sure we are called again until all childs have been reaped */
738 ev_feed_event (EV_A_ (W)sw, EV_SIGNAL);
740 child_reap (EV_A_ sw, pid, pid, status);
741 child_reap (EV_A_ sw, 0, pid, status); /* this might trigger a watcher twice, but event catches that */
747 /*****************************************************************************/
750 # include "ev_port.c"
753 # include "ev_kqueue.c"
756 # include "ev_epoll.c"
759 # include "ev_poll.c"
762 # include "ev_select.c"
766 ev_version_major (void)
768 return EV_VERSION_MAJOR;
772 ev_version_minor (void)
774 return EV_VERSION_MINOR;
777 /* return true if we are running with elevated privileges and should ignore env variables */
784 return getuid () != geteuid ()
785 || getgid () != getegid ();
796 loop_init (EV_P_ unsigned int flags)
803 if (!clock_gettime (CLOCK_MONOTONIC, &ts))
808 ev_rt_now = ev_time ();
809 mn_now = get_clock ();
811 rtmn_diff = ev_rt_now - mn_now;
813 if (!(flags & EVFLAG_NOENV) && !enable_secure () && getenv ("LIBEV_FLAGS"))
814 flags = atoi (getenv ("LIBEV_FLAGS"));
816 if (!(flags & 0x0000ffff))
821 if (!method && (flags & EVMETHOD_PORT )) method = port_init (EV_A_ flags);
824 if (!method && (flags & EVMETHOD_KQUEUE)) method = kqueue_init (EV_A_ flags);
827 if (!method && (flags & EVMETHOD_EPOLL )) method = epoll_init (EV_A_ flags);
830 if (!method && (flags & EVMETHOD_POLL )) method = poll_init (EV_A_ flags);
833 if (!method && (flags & EVMETHOD_SELECT)) method = select_init (EV_A_ flags);
836 ev_init (&sigev, sigcb);
837 ev_set_priority (&sigev, EV_MAXPRI);
847 if (method == EVMETHOD_PORT ) port_destroy (EV_A);
850 if (method == EVMETHOD_KQUEUE) kqueue_destroy (EV_A);
853 if (method == EVMETHOD_EPOLL ) epoll_destroy (EV_A);
856 if (method == EVMETHOD_POLL ) poll_destroy (EV_A);
859 if (method == EVMETHOD_SELECT) select_destroy (EV_A);
862 for (i = NUMPRI; i--; )
863 array_free (pending, [i]);
865 /* have to use the microsoft-never-gets-it-right macro */
866 array_free (fdchange, EMPTY0);
867 array_free (timer, EMPTY0);
869 array_free (periodic, EMPTY0);
871 array_free (idle, EMPTY0);
872 array_free (prepare, EMPTY0);
873 array_free (check, EMPTY0);
882 if (method == EVMETHOD_PORT ) port_fork (EV_A);
885 if (method == EVMETHOD_KQUEUE) kqueue_fork (EV_A);
888 if (method == EVMETHOD_EPOLL ) epoll_fork (EV_A);
891 if (ev_is_active (&sigev))
896 ev_io_stop (EV_A_ &sigev);
900 while (pipe (sigpipe))
901 syserr ("(libev) error creating pipe");
911 ev_loop_new (unsigned int flags)
913 struct ev_loop *loop = (struct ev_loop *)ev_malloc (sizeof (struct ev_loop));
915 memset (loop, 0, sizeof (struct ev_loop));
917 loop_init (EV_A_ flags);
919 if (ev_method (EV_A))
926 ev_loop_destroy (EV_P)
942 ev_default_loop_init (unsigned int flags)
945 ev_default_loop (unsigned int flags)
948 if (sigpipe [0] == sigpipe [1])
952 if (!ev_default_loop_ptr)
955 struct ev_loop *loop = ev_default_loop_ptr = &default_loop_struct;
957 ev_default_loop_ptr = 1;
960 loop_init (EV_A_ flags);
962 if (ev_method (EV_A))
967 ev_signal_init (&childev, childcb, SIGCHLD);
968 ev_set_priority (&childev, EV_MAXPRI);
969 ev_signal_start (EV_A_ &childev);
970 ev_unref (EV_A); /* child watcher should not keep loop alive */
974 ev_default_loop_ptr = 0;
977 return ev_default_loop_ptr;
981 ev_default_destroy (void)
984 struct ev_loop *loop = ev_default_loop_ptr;
988 ev_ref (EV_A); /* child watcher */
989 ev_signal_stop (EV_A_ &childev);
992 ev_ref (EV_A); /* signal watcher */
993 ev_io_stop (EV_A_ &sigev);
995 close (sigpipe [0]); sigpipe [0] = 0;
996 close (sigpipe [1]); sigpipe [1] = 0;
1002 ev_default_fork (void)
1005 struct ev_loop *loop = ev_default_loop_ptr;
1012 /*****************************************************************************/
1019 for (pri = NUMPRI; pri--; )
1020 if (pendingcnt [pri])
1031 for (pri = NUMPRI; pri--; )
1032 while (pendingcnt [pri])
1034 ANPENDING *p = pendings [pri] + --pendingcnt [pri];
1036 if (expect_true (p->w))
1039 EV_CB_INVOKE (p->w, p->events);
1047 while (timercnt && ((WT)timers [0])->at <= mn_now)
1049 struct ev_timer *w = timers [0];
1051 assert (("inactive timer on timer heap detected", ev_is_active (w)));
1053 /* first reschedule or stop timer */
1056 assert (("negative ev_timer repeat value found while processing timers", w->repeat > 0.));
1058 ((WT)w)->at += w->repeat;
1059 if (((WT)w)->at < mn_now)
1060 ((WT)w)->at = mn_now;
1062 downheap ((WT *)timers, timercnt, 0);
1065 ev_timer_stop (EV_A_ w); /* nonrepeating: stop timer */
1067 ev_feed_event (EV_A_ (W)w, EV_TIMEOUT);
1073 periodics_reify (EV_P)
1075 while (periodiccnt && ((WT)periodics [0])->at <= ev_rt_now)
1077 struct ev_periodic *w = periodics [0];
1079 assert (("inactive timer on periodic heap detected", ev_is_active (w)));
1081 /* first reschedule or stop timer */
1082 if (w->reschedule_cb)
1084 ((WT)w)->at = w->reschedule_cb (w, ev_rt_now + 0.0001);
1085 assert (("ev_periodic reschedule callback returned time in the past", ((WT)w)->at > ev_rt_now));
1086 downheap ((WT *)periodics, periodiccnt, 0);
1088 else if (w->interval)
1090 ((WT)w)->at += floor ((ev_rt_now - ((WT)w)->at) / w->interval + 1.) * w->interval;
1091 assert (("ev_periodic timeout in the past detected while processing timers, negative interval?", ((WT)w)->at > ev_rt_now));
1092 downheap ((WT *)periodics, periodiccnt, 0);
1095 ev_periodic_stop (EV_A_ w); /* nonrepeating: stop timer */
1097 ev_feed_event (EV_A_ (W)w, EV_PERIODIC);
1102 periodics_reschedule (EV_P)
1106 /* adjust periodics after time jump */
1107 for (i = 0; i < periodiccnt; ++i)
1109 struct ev_periodic *w = periodics [i];
1111 if (w->reschedule_cb)
1112 ((WT)w)->at = w->reschedule_cb (w, ev_rt_now);
1113 else if (w->interval)
1114 ((WT)w)->at += ceil ((ev_rt_now - ((WT)w)->at) / w->interval) * w->interval;
1117 /* now rebuild the heap */
1118 for (i = periodiccnt >> 1; i--; )
1119 downheap ((WT *)periodics, periodiccnt, i);
1124 time_update_monotonic (EV_P)
1126 mn_now = get_clock ();
1128 if (expect_true (mn_now - now_floor < MIN_TIMEJUMP * .5))
1130 ev_rt_now = rtmn_diff + mn_now;
1136 ev_rt_now = ev_time ();
1146 #if EV_USE_MONOTONIC
1147 if (expect_true (have_monotonic))
1149 if (time_update_monotonic (EV_A))
1151 ev_tstamp odiff = rtmn_diff;
1153 for (i = 4; --i; ) /* loop a few times, before making important decisions */
1155 rtmn_diff = ev_rt_now - mn_now;
1157 if (fabs (odiff - rtmn_diff) < MIN_TIMEJUMP)
1158 return; /* all is well */
1160 ev_rt_now = ev_time ();
1161 mn_now = get_clock ();
1166 periodics_reschedule (EV_A);
1168 /* no timer adjustment, as the monotonic clock doesn't jump */
1169 /* timers_reschedule (EV_A_ rtmn_diff - odiff) */
1175 ev_rt_now = ev_time ();
1177 if (expect_false (mn_now > ev_rt_now || mn_now < ev_rt_now - MAX_BLOCKTIME - MIN_TIMEJUMP))
1180 periodics_reschedule (EV_A);
1183 /* adjust timers. this is easy, as the offset is the same for all */
1184 for (i = 0; i < timercnt; ++i)
1185 ((WT)timers [i])->at += ev_rt_now - mn_now;
1204 static int loop_done;
1207 ev_loop (EV_P_ int flags)
1210 loop_done = flags & (EVLOOP_ONESHOT | EVLOOP_NONBLOCK) ? 1 : 0;
1214 /* queue check watchers (and execute them) */
1215 if (expect_false (preparecnt))
1217 queue_events (EV_A_ (W *)prepares, preparecnt, EV_PREPARE);
1218 call_pending (EV_A);
1221 /* we might have forked, so reify kernel state if necessary */
1222 if (expect_false (postfork))
1225 /* update fd-related kernel structures */
1228 /* calculate blocking time */
1230 /* we only need this for !monotonic clock or timers, but as we basically
1231 always have timers, we just calculate it always */
1232 #if EV_USE_MONOTONIC
1233 if (expect_true (have_monotonic))
1234 time_update_monotonic (EV_A);
1238 ev_rt_now = ev_time ();
1242 if (flags & EVLOOP_NONBLOCK || idlecnt)
1246 block = MAX_BLOCKTIME;
1250 ev_tstamp to = ((WT)timers [0])->at - mn_now + method_fudge;
1251 if (block > to) block = to;
1257 ev_tstamp to = ((WT)periodics [0])->at - ev_rt_now + method_fudge;
1258 if (block > to) block = to;
1262 if (expect_false (block < 0.)) block = 0.;
1265 method_poll (EV_A_ block);
1267 /* update ev_rt_now, do magic */
1270 /* queue pending timers and reschedule them */
1271 timers_reify (EV_A); /* relative timers called last */
1273 periodics_reify (EV_A); /* absolute timers called first */
1276 /* queue idle watchers unless io or timers are pending */
1277 if (idlecnt && !any_pending (EV_A))
1278 queue_events (EV_A_ (W *)idles, idlecnt, EV_IDLE);
1280 /* queue check watchers, to be executed first */
1281 if (expect_false (checkcnt))
1282 queue_events (EV_A_ (W *)checks, checkcnt, EV_CHECK);
1284 call_pending (EV_A);
1286 if (expect_false (loop_done))
1295 ev_unloop (EV_P_ int how)
1300 /*****************************************************************************/
1303 wlist_add (WL *head, WL elem)
1310 wlist_del (WL *head, WL elem)
1320 head = &(*head)->next;
1325 ev_clear_pending (EV_P_ W w)
1329 pendings [ABSPRI (w)][w->pending - 1].w = 0;
1335 ev_start (EV_P_ W w, int active)
1337 if (w->priority < EV_MINPRI) w->priority = EV_MINPRI;
1338 if (w->priority > EV_MAXPRI) w->priority = EV_MAXPRI;
1351 /*****************************************************************************/
1354 ev_io_start (EV_P_ struct ev_io *w)
1358 if (expect_false (ev_is_active (w)))
1361 assert (("ev_io_start called with negative fd", fd >= 0));
1363 ev_start (EV_A_ (W)w, 1);
1364 array_needsize (ANFD, anfds, anfdmax, fd + 1, anfds_init);
1365 wlist_add ((WL *)&anfds[fd].head, (WL)w);
1367 fd_change (EV_A_ fd);
1371 ev_io_stop (EV_P_ struct ev_io *w)
1373 ev_clear_pending (EV_A_ (W)w);
1374 if (expect_false (!ev_is_active (w)))
1377 assert (("ev_io_start called with illegal fd (must stay constant after start!)", w->fd >= 0 && w->fd < anfdmax));
1379 wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
1380 ev_stop (EV_A_ (W)w);
1382 fd_change (EV_A_ w->fd);
1386 ev_timer_start (EV_P_ struct ev_timer *w)
1388 if (expect_false (ev_is_active (w)))
1391 ((WT)w)->at += mn_now;
1393 assert (("ev_timer_start called with negative timer repeat value", w->repeat >= 0.));
1395 ev_start (EV_A_ (W)w, ++timercnt);
1396 array_needsize (struct ev_timer *, timers, timermax, timercnt, EMPTY2);
1397 timers [timercnt - 1] = w;
1398 upheap ((WT *)timers, timercnt - 1);
1400 assert (("internal timer heap corruption", timers [((W)w)->active - 1] == w));
1404 ev_timer_stop (EV_P_ struct ev_timer *w)
1406 ev_clear_pending (EV_A_ (W)w);
1407 if (expect_false (!ev_is_active (w)))
1410 assert (("internal timer heap corruption", timers [((W)w)->active - 1] == w));
1412 if (expect_true (((W)w)->active < timercnt--))
1414 timers [((W)w)->active - 1] = timers [timercnt];
1415 adjustheap ((WT *)timers, timercnt, ((W)w)->active - 1);
1418 ((WT)w)->at -= mn_now;
1420 ev_stop (EV_A_ (W)w);
1424 ev_timer_again (EV_P_ struct ev_timer *w)
1426 if (ev_is_active (w))
1430 ((WT)w)->at = mn_now + w->repeat;
1431 adjustheap ((WT *)timers, timercnt, ((W)w)->active - 1);
1434 ev_timer_stop (EV_A_ w);
1439 ev_timer_start (EV_A_ w);
1445 ev_periodic_start (EV_P_ struct ev_periodic *w)
1447 if (expect_false (ev_is_active (w)))
1450 if (w->reschedule_cb)
1451 ((WT)w)->at = w->reschedule_cb (w, ev_rt_now);
1452 else if (w->interval)
1454 assert (("ev_periodic_start called with negative interval value", w->interval >= 0.));
1455 /* this formula differs from the one in periodic_reify because we do not always round up */
1456 ((WT)w)->at += ceil ((ev_rt_now - ((WT)w)->at) / w->interval) * w->interval;
1459 ev_start (EV_A_ (W)w, ++periodiccnt);
1460 array_needsize (struct ev_periodic *, periodics, periodicmax, periodiccnt, EMPTY2);
1461 periodics [periodiccnt - 1] = w;
1462 upheap ((WT *)periodics, periodiccnt - 1);
1464 assert (("internal periodic heap corruption", periodics [((W)w)->active - 1] == w));
1468 ev_periodic_stop (EV_P_ struct ev_periodic *w)
1470 ev_clear_pending (EV_A_ (W)w);
1471 if (expect_false (!ev_is_active (w)))
1474 assert (("internal periodic heap corruption", periodics [((W)w)->active - 1] == w));
1476 if (expect_true (((W)w)->active < periodiccnt--))
1478 periodics [((W)w)->active - 1] = periodics [periodiccnt];
1479 adjustheap ((WT *)periodics, periodiccnt, ((W)w)->active - 1);
1482 ev_stop (EV_A_ (W)w);
1486 ev_periodic_again (EV_P_ struct ev_periodic *w)
1488 /* TODO: use adjustheap and recalculation */
1489 ev_periodic_stop (EV_A_ w);
1490 ev_periodic_start (EV_A_ w);
1495 ev_idle_start (EV_P_ struct ev_idle *w)
1497 if (expect_false (ev_is_active (w)))
1500 ev_start (EV_A_ (W)w, ++idlecnt);
1501 array_needsize (struct ev_idle *, idles, idlemax, idlecnt, EMPTY2);
1502 idles [idlecnt - 1] = w;
1506 ev_idle_stop (EV_P_ struct ev_idle *w)
1508 ev_clear_pending (EV_A_ (W)w);
1509 if (expect_false (!ev_is_active (w)))
1512 idles [((W)w)->active - 1] = idles [--idlecnt];
1513 ev_stop (EV_A_ (W)w);
1517 ev_prepare_start (EV_P_ struct ev_prepare *w)
1519 if (expect_false (ev_is_active (w)))
1522 ev_start (EV_A_ (W)w, ++preparecnt);
1523 array_needsize (struct ev_prepare *, prepares, preparemax, preparecnt, EMPTY2);
1524 prepares [preparecnt - 1] = w;
1528 ev_prepare_stop (EV_P_ struct ev_prepare *w)
1530 ev_clear_pending (EV_A_ (W)w);
1531 if (expect_false (!ev_is_active (w)))
1534 prepares [((W)w)->active - 1] = prepares [--preparecnt];
1535 ev_stop (EV_A_ (W)w);
1539 ev_check_start (EV_P_ struct ev_check *w)
1541 if (expect_false (ev_is_active (w)))
1544 ev_start (EV_A_ (W)w, ++checkcnt);
1545 array_needsize (struct ev_check *, checks, checkmax, checkcnt, EMPTY2);
1546 checks [checkcnt - 1] = w;
1550 ev_check_stop (EV_P_ struct ev_check *w)
1552 ev_clear_pending (EV_A_ (W)w);
1553 if (expect_false (!ev_is_active (w)))
1556 checks [((W)w)->active - 1] = checks [--checkcnt];
1557 ev_stop (EV_A_ (W)w);
1561 # define SA_RESTART 0
1565 ev_signal_start (EV_P_ struct ev_signal *w)
1568 assert (("signal watchers are only supported in the default loop", loop == ev_default_loop_ptr));
1570 if (expect_false (ev_is_active (w)))
1573 assert (("ev_signal_start called with illegal signal number", w->signum > 0));
1575 ev_start (EV_A_ (W)w, 1);
1576 array_needsize (ANSIG, signals, signalmax, w->signum, signals_init);
1577 wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
1582 signal (w->signum, sighandler);
1584 struct sigaction sa;
1585 sa.sa_handler = sighandler;
1586 sigfillset (&sa.sa_mask);
1587 sa.sa_flags = SA_RESTART; /* if restarting works we save one iteration */
1588 sigaction (w->signum, &sa, 0);
1594 ev_signal_stop (EV_P_ struct ev_signal *w)
1596 ev_clear_pending (EV_A_ (W)w);
1597 if (expect_false (!ev_is_active (w)))
1600 wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
1601 ev_stop (EV_A_ (W)w);
1603 if (!signals [w->signum - 1].head)
1604 signal (w->signum, SIG_DFL);
1608 ev_child_start (EV_P_ struct ev_child *w)
1611 assert (("child watchers are only supported in the default loop", loop == ev_default_loop_ptr));
1613 if (expect_false (ev_is_active (w)))
1616 ev_start (EV_A_ (W)w, 1);
1617 wlist_add ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
1621 ev_child_stop (EV_P_ struct ev_child *w)
1623 ev_clear_pending (EV_A_ (W)w);
1624 if (expect_false (!ev_is_active (w)))
1627 wlist_del ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
1628 ev_stop (EV_A_ (W)w);
1631 /*****************************************************************************/
1637 void (*cb)(int revents, void *arg);
1642 once_cb (EV_P_ struct ev_once *once, int revents)
1644 void (*cb)(int revents, void *arg) = once->cb;
1645 void *arg = once->arg;
1647 ev_io_stop (EV_A_ &once->io);
1648 ev_timer_stop (EV_A_ &once->to);
1655 once_cb_io (EV_P_ struct ev_io *w, int revents)
1657 once_cb (EV_A_ (struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
1661 once_cb_to (EV_P_ struct ev_timer *w, int revents)
1663 once_cb (EV_A_ (struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
1667 ev_once (EV_P_ int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
1669 struct ev_once *once = (struct ev_once *)ev_malloc (sizeof (struct ev_once));
1671 if (expect_false (!once))
1673 cb (EV_ERROR | EV_READ | EV_WRITE | EV_TIMEOUT, arg);
1680 ev_init (&once->io, once_cb_io);
1683 ev_io_set (&once->io, fd, events);
1684 ev_io_start (EV_A_ &once->io);
1687 ev_init (&once->to, once_cb_to);
1690 ev_timer_set (&once->to, timeout, 0.);
1691 ev_timer_start (EV_A_ &once->to);