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 # if HAVE_SELECT && HAVE_SYS_SELECT_H && !defined (EV_USE_SELECT)
56 # define EV_USE_SELECT 1
58 # define EV_USE_SELECT 0
61 # if HAVE_POLL && HAVE_POLL_H && !defined (EV_USE_POLL)
62 # define EV_USE_POLL 1
64 # define EV_USE_POLL 0
67 # if HAVE_EPOLL_CTL && HAVE_SYS_EPOLL_H && !defined (EV_USE_EPOLL)
68 # define EV_USE_EPOLL 1
70 # define EV_USE_EPOLL 0
73 # if HAVE_KQUEUE && HAVE_SYS_EVENT_H && HAVE_SYS_QUEUE_H && !defined (EV_USE_KQUEUE)
74 # define EV_USE_KQUEUE 1
76 # define EV_USE_KQUEUE 0
79 # if HAVE_PORT_H && HAVE_PORT_CREATE && !defined (EV_USE_PORT)
80 # define EV_USE_PORT 1
82 # define EV_USE_PORT 0
96 #include <sys/types.h>
103 # include <sys/time.h>
104 # include <sys/wait.h>
106 # define WIN32_LEAN_AND_MEAN
107 # include <windows.h>
108 # ifndef EV_SELECT_IS_WINSOCKET
109 # define EV_SELECT_IS_WINSOCKET 1
115 #ifndef EV_USE_MONOTONIC
116 # define EV_USE_MONOTONIC 0
119 #ifndef EV_USE_REALTIME
120 # define EV_USE_REALTIME 0
123 #ifndef EV_USE_SELECT
124 # define EV_USE_SELECT 1
129 # define EV_USE_POLL 0
131 # define EV_USE_POLL 1
136 # define EV_USE_EPOLL 0
139 #ifndef EV_USE_KQUEUE
140 # define EV_USE_KQUEUE 0
144 # define EV_USE_PORT 0
149 /* darwin simply cannot be helped */
152 # undef EV_USE_KQUEUE
155 #ifndef CLOCK_MONOTONIC
156 # undef EV_USE_MONOTONIC
157 # define EV_USE_MONOTONIC 0
160 #ifndef CLOCK_REALTIME
161 # undef EV_USE_REALTIME
162 # define EV_USE_REALTIME 0
165 #if EV_SELECT_IS_WINSOCKET
166 # include <winsock.h>
171 #define MIN_TIMEJUMP 1. /* minimum timejump that gets detected (if monotonic clock available) */
172 #define MAX_BLOCKTIME 59.743 /* never wait longer than this time (to detect time jumps) */
173 #define PID_HASHSIZE 16 /* size of pid hash table, must be power of two */
174 /*#define CLEANUP_INTERVAL (MAX_BLOCKTIME * 5.) /* how often to try to free memory and re-check fds */
183 # define expect(expr,value) __builtin_expect ((expr),(value))
184 # define inline static inline
186 # define expect(expr,value) (expr)
187 # define inline static
190 #define expect_false(expr) expect ((expr) != 0, 0)
191 #define expect_true(expr) expect ((expr) != 0, 1)
193 #define NUMPRI (EV_MAXPRI - EV_MINPRI + 1)
194 #define ABSPRI(w) ((w)->priority - EV_MINPRI)
196 #define EMPTY0 /* required for microsofts broken pseudo-c compiler */
197 #define EMPTY2(a,b) /* used to suppress some warnings */
199 typedef struct ev_watcher *W;
200 typedef struct ev_watcher_list *WL;
201 typedef struct ev_watcher_time *WT;
203 static int have_monotonic; /* did clock_gettime (CLOCK_MONOTONIC) work? */
206 # include "ev_win32.c"
209 /*****************************************************************************/
211 static void (*syserr_cb)(const char *msg);
213 void ev_set_syserr_cb (void (*cb)(const char *msg))
219 syserr (const char *msg)
222 msg = "(libev) system error";
233 static void *(*alloc)(void *ptr, long size);
235 void ev_set_allocator (void *(*cb)(void *ptr, long size))
241 ev_realloc (void *ptr, long size)
243 ptr = alloc ? alloc (ptr, size) : realloc (ptr, size);
247 fprintf (stderr, "libev: cannot allocate %ld bytes, aborting.", size);
254 #define ev_malloc(size) ev_realloc (0, (size))
255 #define ev_free(ptr) ev_realloc ((ptr), 0)
257 /*****************************************************************************/
262 unsigned char events;
264 #if EV_SELECT_IS_WINSOCKET
280 #define ev_rt_now ((loop)->ev_rt_now)
281 #define VAR(name,decl) decl;
287 static struct ev_loop default_loop_struct;
288 struct ev_loop *ev_default_loop_ptr;
293 #define VAR(name,decl) static decl;
297 static int ev_default_loop_ptr;
301 /*****************************************************************************/
308 clock_gettime (CLOCK_REALTIME, &ts);
309 return ts.tv_sec + ts.tv_nsec * 1e-9;
312 gettimeofday (&tv, 0);
313 return tv.tv_sec + tv.tv_usec * 1e-6;
321 if (expect_true (have_monotonic))
324 clock_gettime (CLOCK_MONOTONIC, &ts);
325 return ts.tv_sec + ts.tv_nsec * 1e-9;
340 #define array_roundsize(type,n) (((n) | 4) & ~3)
342 #define array_needsize(type,base,cur,cnt,init) \
343 if (expect_false ((cnt) > cur)) \
348 newcnt = array_roundsize (type, newcnt << 1); \
350 while ((cnt) > newcnt); \
352 base = (type *)ev_realloc (base, sizeof (type) * (newcnt));\
353 init (base + cur, newcnt - cur); \
357 #define array_slim(type,stem) \
358 if (stem ## max < array_roundsize (stem ## cnt >> 2)) \
360 stem ## max = array_roundsize (stem ## cnt >> 1); \
361 base = (type *)ev_realloc (base, sizeof (type) * (stem ## max));\
362 fprintf (stderr, "slimmed down " # stem " to %d\n", stem ## max);/*D*/\
365 #define array_free(stem, idx) \
366 ev_free (stem ## s idx); stem ## cnt idx = stem ## max idx = 0;
368 /*****************************************************************************/
371 anfds_init (ANFD *base, int count)
376 base->events = EV_NONE;
384 ev_feed_event (EV_P_ void *w, int revents)
388 if (expect_false (w_->pending))
390 pendings [ABSPRI (w_)][w_->pending - 1].events |= revents;
394 w_->pending = ++pendingcnt [ABSPRI (w_)];
395 array_needsize (ANPENDING, pendings [ABSPRI (w_)], pendingmax [ABSPRI (w_)], pendingcnt [ABSPRI (w_)], EMPTY2);
396 pendings [ABSPRI (w_)][w_->pending - 1].w = w_;
397 pendings [ABSPRI (w_)][w_->pending - 1].events = revents;
401 queue_events (EV_P_ W *events, int eventcnt, int type)
405 for (i = 0; i < eventcnt; ++i)
406 ev_feed_event (EV_A_ events [i], type);
410 fd_event (EV_P_ int fd, int revents)
412 ANFD *anfd = anfds + fd;
415 for (w = (struct ev_io *)anfd->head; w; w = (struct ev_io *)((WL)w)->next)
417 int ev = w->events & revents;
420 ev_feed_event (EV_A_ (W)w, ev);
425 ev_feed_fd_event (EV_P_ int fd, int revents)
427 fd_event (EV_A_ fd, revents);
430 /*****************************************************************************/
437 for (i = 0; i < fdchangecnt; ++i)
439 int fd = fdchanges [i];
440 ANFD *anfd = anfds + fd;
445 for (w = (struct ev_io *)anfd->head; w; w = (struct ev_io *)((WL)w)->next)
448 #if EV_SELECT_IS_WINSOCKET
452 anfd->handle = _get_osfhandle (fd);
453 assert (("libev only supports socket fds in this configuration", ioctlsocket (anfd->handle, FIONREAD, &argp) == 0));
459 method_modify (EV_A_ fd, anfd->events, events);
460 anfd->events = events;
467 fd_change (EV_P_ int fd)
469 if (expect_false (anfds [fd].reify))
472 anfds [fd].reify = 1;
475 array_needsize (int, fdchanges, fdchangemax, fdchangecnt, EMPTY2);
476 fdchanges [fdchangecnt - 1] = fd;
480 fd_kill (EV_P_ int fd)
484 while ((w = (struct ev_io *)anfds [fd].head))
486 ev_io_stop (EV_A_ w);
487 ev_feed_event (EV_A_ (W)w, EV_ERROR | EV_READ | EV_WRITE);
495 return _get_osfhandle (fd) != -1;
497 return fcntl (fd, F_GETFD) != -1;
501 /* called on EBADF to verify fds */
507 for (fd = 0; fd < anfdmax; ++fd)
508 if (anfds [fd].events)
509 if (!fd_valid (fd) == -1 && errno == EBADF)
513 /* called on ENOMEM in select/poll to kill some fds and retry */
519 for (fd = anfdmax; fd--; )
520 if (anfds [fd].events)
527 /* usually called after fork if method needs to re-arm all fds from scratch */
533 /* this should be highly optimised to not do anything but set a flag */
534 for (fd = 0; fd < anfdmax; ++fd)
535 if (anfds [fd].events)
537 anfds [fd].events = 0;
538 fd_change (EV_A_ fd);
542 /*****************************************************************************/
545 upheap (WT *heap, int k)
549 while (k && heap [k >> 1]->at > w->at)
551 heap [k] = heap [k >> 1];
552 ((W)heap [k])->active = k + 1;
557 ((W)heap [k])->active = k + 1;
562 downheap (WT *heap, int N, int k)
570 if (j + 1 < N && heap [j]->at > heap [j + 1]->at)
573 if (w->at <= heap [j]->at)
577 ((W)heap [k])->active = k + 1;
582 ((W)heap [k])->active = k + 1;
586 adjustheap (WT *heap, int N, int k)
589 downheap (heap, N, k);
592 /*****************************************************************************/
597 sig_atomic_t volatile gotsig;
600 static ANSIG *signals;
601 static int signalmax;
603 static int sigpipe [2];
604 static sig_atomic_t volatile gotsig;
605 static struct ev_io sigev;
608 signals_init (ANSIG *base, int count)
620 sighandler (int signum)
623 signal (signum, sighandler);
626 signals [signum - 1].gotsig = 1;
630 int old_errno = errno;
632 write (sigpipe [1], &signum, 1);
638 ev_feed_signal_event (EV_P_ int signum)
643 assert (("feeding signal events is only supported in the default loop", loop == ev_default_loop_ptr));
648 if (signum < 0 || signum >= signalmax)
651 signals [signum].gotsig = 0;
653 for (w = signals [signum].head; w; w = w->next)
654 ev_feed_event (EV_A_ (W)w, EV_SIGNAL);
658 sigcb (EV_P_ struct ev_io *iow, int revents)
662 read (sigpipe [0], &revents, 1);
665 for (signum = signalmax; signum--; )
666 if (signals [signum].gotsig)
667 ev_feed_signal_event (EV_A_ signum + 1);
675 ioctlsocket (_get_osfhandle (fd), FIONBIO, &arg);
677 fcntl (fd, F_SETFD, FD_CLOEXEC);
678 fcntl (fd, F_SETFL, O_NONBLOCK);
685 fd_intern (sigpipe [0]);
686 fd_intern (sigpipe [1]);
688 ev_io_set (&sigev, sigpipe [0], EV_READ);
689 ev_io_start (EV_A_ &sigev);
690 ev_unref (EV_A); /* child watcher should not keep loop alive */
693 /*****************************************************************************/
695 static struct ev_child *childs [PID_HASHSIZE];
699 static struct ev_signal childev;
702 # define WCONTINUED 0
706 child_reap (EV_P_ struct ev_signal *sw, int chain, int pid, int status)
710 for (w = (struct ev_child *)childs [chain & (PID_HASHSIZE - 1)]; w; w = (struct ev_child *)((WL)w)->next)
711 if (w->pid == pid || !w->pid)
713 ev_priority (w) = ev_priority (sw); /* need to do it *now* */
716 ev_feed_event (EV_A_ (W)w, EV_CHILD);
721 childcb (EV_P_ struct ev_signal *sw, int revents)
725 if (0 < (pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED)))
727 /* make sure we are called again until all childs have been reaped */
728 ev_feed_event (EV_A_ (W)sw, EV_SIGNAL);
730 child_reap (EV_A_ sw, pid, pid, status);
731 child_reap (EV_A_ sw, 0, pid, status); /* this might trigger a watcher twice, but event catches that */
737 /*****************************************************************************/
740 # include "ev_port.c"
743 # include "ev_kqueue.c"
746 # include "ev_epoll.c"
749 # include "ev_poll.c"
752 # include "ev_select.c"
756 ev_version_major (void)
758 return EV_VERSION_MAJOR;
762 ev_version_minor (void)
764 return EV_VERSION_MINOR;
767 /* return true if we are running with elevated privileges and should ignore env variables */
774 return getuid () != geteuid ()
775 || getgid () != getegid ();
786 loop_init (EV_P_ unsigned int flags)
793 if (!clock_gettime (CLOCK_MONOTONIC, &ts))
798 ev_rt_now = ev_time ();
799 mn_now = get_clock ();
801 rtmn_diff = ev_rt_now - mn_now;
803 if (!(flags & EVFLAG_NOENV) && !enable_secure () && getenv ("LIBEV_FLAGS"))
804 flags = atoi (getenv ("LIBEV_FLAGS"));
806 if (!(flags & 0x0000ffff))
811 if (!method && (flags & EVMETHOD_PORT )) method = port_init (EV_A_ flags);
814 if (!method && (flags & EVMETHOD_KQUEUE)) method = kqueue_init (EV_A_ flags);
817 if (!method && (flags & EVMETHOD_EPOLL )) method = epoll_init (EV_A_ flags);
820 if (!method && (flags & EVMETHOD_POLL )) method = poll_init (EV_A_ flags);
823 if (!method && (flags & EVMETHOD_SELECT)) method = select_init (EV_A_ flags);
826 ev_init (&sigev, sigcb);
827 ev_set_priority (&sigev, EV_MAXPRI);
837 if (method == EVMETHOD_PORT ) port_destroy (EV_A);
840 if (method == EVMETHOD_KQUEUE) kqueue_destroy (EV_A);
843 if (method == EVMETHOD_EPOLL ) epoll_destroy (EV_A);
846 if (method == EVMETHOD_POLL ) poll_destroy (EV_A);
849 if (method == EVMETHOD_SELECT) select_destroy (EV_A);
852 for (i = NUMPRI; i--; )
853 array_free (pending, [i]);
855 /* have to use the microsoft-never-gets-it-right macro */
856 array_free (fdchange, EMPTY0);
857 array_free (timer, EMPTY0);
859 array_free (periodic, EMPTY0);
861 array_free (idle, EMPTY0);
862 array_free (prepare, EMPTY0);
863 array_free (check, EMPTY0);
872 if (method == EVMETHOD_PORT ) port_fork (EV_A);
875 if (method == EVMETHOD_KQUEUE) kqueue_fork (EV_A);
878 if (method == EVMETHOD_EPOLL ) epoll_fork (EV_A);
881 if (ev_is_active (&sigev))
886 ev_io_stop (EV_A_ &sigev);
890 while (pipe (sigpipe))
891 syserr ("(libev) error creating pipe");
901 ev_loop_new (unsigned int flags)
903 struct ev_loop *loop = (struct ev_loop *)ev_malloc (sizeof (struct ev_loop));
905 memset (loop, 0, sizeof (struct ev_loop));
907 loop_init (EV_A_ flags);
909 if (ev_method (EV_A))
916 ev_loop_destroy (EV_P)
932 ev_default_loop_init (unsigned int flags)
935 ev_default_loop (unsigned int flags)
938 if (sigpipe [0] == sigpipe [1])
942 if (!ev_default_loop_ptr)
945 struct ev_loop *loop = ev_default_loop_ptr = &default_loop_struct;
947 ev_default_loop_ptr = 1;
950 loop_init (EV_A_ flags);
952 if (ev_method (EV_A))
957 ev_signal_init (&childev, childcb, SIGCHLD);
958 ev_set_priority (&childev, EV_MAXPRI);
959 ev_signal_start (EV_A_ &childev);
960 ev_unref (EV_A); /* child watcher should not keep loop alive */
964 ev_default_loop_ptr = 0;
967 return ev_default_loop_ptr;
971 ev_default_destroy (void)
974 struct ev_loop *loop = ev_default_loop_ptr;
978 ev_ref (EV_A); /* child watcher */
979 ev_signal_stop (EV_A_ &childev);
982 ev_ref (EV_A); /* signal watcher */
983 ev_io_stop (EV_A_ &sigev);
985 close (sigpipe [0]); sigpipe [0] = 0;
986 close (sigpipe [1]); sigpipe [1] = 0;
992 ev_default_fork (void)
995 struct ev_loop *loop = ev_default_loop_ptr;
1002 /*****************************************************************************/
1009 for (pri = NUMPRI; pri--; )
1010 if (pendingcnt [pri])
1021 for (pri = NUMPRI; pri--; )
1022 while (pendingcnt [pri])
1024 ANPENDING *p = pendings [pri] + --pendingcnt [pri];
1026 if (expect_true (p->w))
1029 EV_CB_INVOKE (p->w, p->events);
1037 while (timercnt && ((WT)timers [0])->at <= mn_now)
1039 struct ev_timer *w = timers [0];
1041 assert (("inactive timer on timer heap detected", ev_is_active (w)));
1043 /* first reschedule or stop timer */
1046 assert (("negative ev_timer repeat value found while processing timers", w->repeat > 0.));
1048 ((WT)w)->at += w->repeat;
1049 if (((WT)w)->at < mn_now)
1050 ((WT)w)->at = mn_now;
1052 downheap ((WT *)timers, timercnt, 0);
1055 ev_timer_stop (EV_A_ w); /* nonrepeating: stop timer */
1057 ev_feed_event (EV_A_ (W)w, EV_TIMEOUT);
1063 periodics_reify (EV_P)
1065 while (periodiccnt && ((WT)periodics [0])->at <= ev_rt_now)
1067 struct ev_periodic *w = periodics [0];
1069 assert (("inactive timer on periodic heap detected", ev_is_active (w)));
1071 /* first reschedule or stop timer */
1072 if (w->reschedule_cb)
1074 ((WT)w)->at = w->reschedule_cb (w, ev_rt_now + 0.0001);
1075 assert (("ev_periodic reschedule callback returned time in the past", ((WT)w)->at > ev_rt_now));
1076 downheap ((WT *)periodics, periodiccnt, 0);
1078 else if (w->interval)
1080 ((WT)w)->at += floor ((ev_rt_now - ((WT)w)->at) / w->interval + 1.) * w->interval;
1081 assert (("ev_periodic timeout in the past detected while processing timers, negative interval?", ((WT)w)->at > ev_rt_now));
1082 downheap ((WT *)periodics, periodiccnt, 0);
1085 ev_periodic_stop (EV_A_ w); /* nonrepeating: stop timer */
1087 ev_feed_event (EV_A_ (W)w, EV_PERIODIC);
1092 periodics_reschedule (EV_P)
1096 /* adjust periodics after time jump */
1097 for (i = 0; i < periodiccnt; ++i)
1099 struct ev_periodic *w = periodics [i];
1101 if (w->reschedule_cb)
1102 ((WT)w)->at = w->reschedule_cb (w, ev_rt_now);
1103 else if (w->interval)
1104 ((WT)w)->at += ceil ((ev_rt_now - ((WT)w)->at) / w->interval) * w->interval;
1107 /* now rebuild the heap */
1108 for (i = periodiccnt >> 1; i--; )
1109 downheap ((WT *)periodics, periodiccnt, i);
1114 time_update_monotonic (EV_P)
1116 mn_now = get_clock ();
1118 if (expect_true (mn_now - now_floor < MIN_TIMEJUMP * .5))
1120 ev_rt_now = rtmn_diff + mn_now;
1126 ev_rt_now = ev_time ();
1136 #if EV_USE_MONOTONIC
1137 if (expect_true (have_monotonic))
1139 if (time_update_monotonic (EV_A))
1141 ev_tstamp odiff = rtmn_diff;
1143 for (i = 4; --i; ) /* loop a few times, before making important decisions */
1145 rtmn_diff = ev_rt_now - mn_now;
1147 if (fabs (odiff - rtmn_diff) < MIN_TIMEJUMP)
1148 return; /* all is well */
1150 ev_rt_now = ev_time ();
1151 mn_now = get_clock ();
1156 periodics_reschedule (EV_A);
1158 /* no timer adjustment, as the monotonic clock doesn't jump */
1159 /* timers_reschedule (EV_A_ rtmn_diff - odiff) */
1165 ev_rt_now = ev_time ();
1167 if (expect_false (mn_now > ev_rt_now || mn_now < ev_rt_now - MAX_BLOCKTIME - MIN_TIMEJUMP))
1170 periodics_reschedule (EV_A);
1173 /* adjust timers. this is easy, as the offset is the same for all */
1174 for (i = 0; i < timercnt; ++i)
1175 ((WT)timers [i])->at += ev_rt_now - mn_now;
1194 static int loop_done;
1197 ev_loop (EV_P_ int flags)
1200 loop_done = flags & (EVLOOP_ONESHOT | EVLOOP_NONBLOCK) ? 1 : 0;
1204 /* queue check watchers (and execute them) */
1205 if (expect_false (preparecnt))
1207 queue_events (EV_A_ (W *)prepares, preparecnt, EV_PREPARE);
1208 call_pending (EV_A);
1211 /* we might have forked, so reify kernel state if necessary */
1212 if (expect_false (postfork))
1215 /* update fd-related kernel structures */
1218 /* calculate blocking time */
1220 /* we only need this for !monotonic clock or timers, but as we basically
1221 always have timers, we just calculate it always */
1222 #if EV_USE_MONOTONIC
1223 if (expect_true (have_monotonic))
1224 time_update_monotonic (EV_A);
1228 ev_rt_now = ev_time ();
1232 if (flags & EVLOOP_NONBLOCK || idlecnt)
1236 block = MAX_BLOCKTIME;
1240 ev_tstamp to = ((WT)timers [0])->at - mn_now + method_fudge;
1241 if (block > to) block = to;
1247 ev_tstamp to = ((WT)periodics [0])->at - ev_rt_now + method_fudge;
1248 if (block > to) block = to;
1252 if (expect_false (block < 0.)) block = 0.;
1255 method_poll (EV_A_ block);
1257 /* update ev_rt_now, do magic */
1260 /* queue pending timers and reschedule them */
1261 timers_reify (EV_A); /* relative timers called last */
1263 periodics_reify (EV_A); /* absolute timers called first */
1266 /* queue idle watchers unless io or timers are pending */
1267 if (idlecnt && !any_pending (EV_A))
1268 queue_events (EV_A_ (W *)idles, idlecnt, EV_IDLE);
1270 /* queue check watchers, to be executed first */
1271 if (expect_false (checkcnt))
1272 queue_events (EV_A_ (W *)checks, checkcnt, EV_CHECK);
1274 call_pending (EV_A);
1276 if (expect_false (loop_done))
1285 ev_unloop (EV_P_ int how)
1290 /*****************************************************************************/
1293 wlist_add (WL *head, WL elem)
1300 wlist_del (WL *head, WL elem)
1310 head = &(*head)->next;
1315 ev_clear_pending (EV_P_ W w)
1319 pendings [ABSPRI (w)][w->pending - 1].w = 0;
1325 ev_start (EV_P_ W w, int active)
1327 if (w->priority < EV_MINPRI) w->priority = EV_MINPRI;
1328 if (w->priority > EV_MAXPRI) w->priority = EV_MAXPRI;
1341 /*****************************************************************************/
1344 ev_io_start (EV_P_ struct ev_io *w)
1348 if (expect_false (ev_is_active (w)))
1351 assert (("ev_io_start called with negative fd", fd >= 0));
1353 ev_start (EV_A_ (W)w, 1);
1354 array_needsize (ANFD, anfds, anfdmax, fd + 1, anfds_init);
1355 wlist_add ((WL *)&anfds[fd].head, (WL)w);
1357 fd_change (EV_A_ fd);
1361 ev_io_stop (EV_P_ struct ev_io *w)
1363 ev_clear_pending (EV_A_ (W)w);
1364 if (expect_false (!ev_is_active (w)))
1367 assert (("ev_io_start called with illegal fd (must stay constant after start!)", w->fd >= 0 && w->fd < anfdmax));
1369 wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
1370 ev_stop (EV_A_ (W)w);
1372 fd_change (EV_A_ w->fd);
1376 ev_timer_start (EV_P_ struct ev_timer *w)
1378 if (expect_false (ev_is_active (w)))
1381 ((WT)w)->at += mn_now;
1383 assert (("ev_timer_start called with negative timer repeat value", w->repeat >= 0.));
1385 ev_start (EV_A_ (W)w, ++timercnt);
1386 array_needsize (struct ev_timer *, timers, timermax, timercnt, EMPTY2);
1387 timers [timercnt - 1] = w;
1388 upheap ((WT *)timers, timercnt - 1);
1390 assert (("internal timer heap corruption", timers [((W)w)->active - 1] == w));
1394 ev_timer_stop (EV_P_ struct ev_timer *w)
1396 ev_clear_pending (EV_A_ (W)w);
1397 if (expect_false (!ev_is_active (w)))
1400 assert (("internal timer heap corruption", timers [((W)w)->active - 1] == w));
1402 if (expect_true (((W)w)->active < timercnt--))
1404 timers [((W)w)->active - 1] = timers [timercnt];
1405 adjustheap ((WT *)timers, timercnt, ((W)w)->active - 1);
1408 ((WT)w)->at -= mn_now;
1410 ev_stop (EV_A_ (W)w);
1414 ev_timer_again (EV_P_ struct ev_timer *w)
1416 if (ev_is_active (w))
1420 ((WT)w)->at = mn_now + w->repeat;
1421 adjustheap ((WT *)timers, timercnt, ((W)w)->active - 1);
1424 ev_timer_stop (EV_A_ w);
1429 ev_timer_start (EV_A_ w);
1435 ev_periodic_start (EV_P_ struct ev_periodic *w)
1437 if (expect_false (ev_is_active (w)))
1440 if (w->reschedule_cb)
1441 ((WT)w)->at = w->reschedule_cb (w, ev_rt_now);
1442 else if (w->interval)
1444 assert (("ev_periodic_start called with negative interval value", w->interval >= 0.));
1445 /* this formula differs from the one in periodic_reify because we do not always round up */
1446 ((WT)w)->at += ceil ((ev_rt_now - ((WT)w)->at) / w->interval) * w->interval;
1449 ev_start (EV_A_ (W)w, ++periodiccnt);
1450 array_needsize (struct ev_periodic *, periodics, periodicmax, periodiccnt, EMPTY2);
1451 periodics [periodiccnt - 1] = w;
1452 upheap ((WT *)periodics, periodiccnt - 1);
1454 assert (("internal periodic heap corruption", periodics [((W)w)->active - 1] == w));
1458 ev_periodic_stop (EV_P_ struct ev_periodic *w)
1460 ev_clear_pending (EV_A_ (W)w);
1461 if (expect_false (!ev_is_active (w)))
1464 assert (("internal periodic heap corruption", periodics [((W)w)->active - 1] == w));
1466 if (expect_true (((W)w)->active < periodiccnt--))
1468 periodics [((W)w)->active - 1] = periodics [periodiccnt];
1469 adjustheap ((WT *)periodics, periodiccnt, ((W)w)->active - 1);
1472 ev_stop (EV_A_ (W)w);
1476 ev_periodic_again (EV_P_ struct ev_periodic *w)
1478 /* TODO: use adjustheap and recalculation */
1479 ev_periodic_stop (EV_A_ w);
1480 ev_periodic_start (EV_A_ w);
1485 ev_idle_start (EV_P_ struct ev_idle *w)
1487 if (expect_false (ev_is_active (w)))
1490 ev_start (EV_A_ (W)w, ++idlecnt);
1491 array_needsize (struct ev_idle *, idles, idlemax, idlecnt, EMPTY2);
1492 idles [idlecnt - 1] = w;
1496 ev_idle_stop (EV_P_ struct ev_idle *w)
1498 ev_clear_pending (EV_A_ (W)w);
1499 if (expect_false (!ev_is_active (w)))
1502 idles [((W)w)->active - 1] = idles [--idlecnt];
1503 ev_stop (EV_A_ (W)w);
1507 ev_prepare_start (EV_P_ struct ev_prepare *w)
1509 if (expect_false (ev_is_active (w)))
1512 ev_start (EV_A_ (W)w, ++preparecnt);
1513 array_needsize (struct ev_prepare *, prepares, preparemax, preparecnt, EMPTY2);
1514 prepares [preparecnt - 1] = w;
1518 ev_prepare_stop (EV_P_ struct ev_prepare *w)
1520 ev_clear_pending (EV_A_ (W)w);
1521 if (expect_false (!ev_is_active (w)))
1524 prepares [((W)w)->active - 1] = prepares [--preparecnt];
1525 ev_stop (EV_A_ (W)w);
1529 ev_check_start (EV_P_ struct ev_check *w)
1531 if (expect_false (ev_is_active (w)))
1534 ev_start (EV_A_ (W)w, ++checkcnt);
1535 array_needsize (struct ev_check *, checks, checkmax, checkcnt, EMPTY2);
1536 checks [checkcnt - 1] = w;
1540 ev_check_stop (EV_P_ struct ev_check *w)
1542 ev_clear_pending (EV_A_ (W)w);
1543 if (expect_false (!ev_is_active (w)))
1546 checks [((W)w)->active - 1] = checks [--checkcnt];
1547 ev_stop (EV_A_ (W)w);
1551 # define SA_RESTART 0
1555 ev_signal_start (EV_P_ struct ev_signal *w)
1558 assert (("signal watchers are only supported in the default loop", loop == ev_default_loop_ptr));
1560 if (expect_false (ev_is_active (w)))
1563 assert (("ev_signal_start called with illegal signal number", w->signum > 0));
1565 ev_start (EV_A_ (W)w, 1);
1566 array_needsize (ANSIG, signals, signalmax, w->signum, signals_init);
1567 wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
1572 signal (w->signum, sighandler);
1574 struct sigaction sa;
1575 sa.sa_handler = sighandler;
1576 sigfillset (&sa.sa_mask);
1577 sa.sa_flags = SA_RESTART; /* if restarting works we save one iteration */
1578 sigaction (w->signum, &sa, 0);
1584 ev_signal_stop (EV_P_ struct ev_signal *w)
1586 ev_clear_pending (EV_A_ (W)w);
1587 if (expect_false (!ev_is_active (w)))
1590 wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
1591 ev_stop (EV_A_ (W)w);
1593 if (!signals [w->signum - 1].head)
1594 signal (w->signum, SIG_DFL);
1598 ev_child_start (EV_P_ struct ev_child *w)
1601 assert (("child watchers are only supported in the default loop", loop == ev_default_loop_ptr));
1603 if (expect_false (ev_is_active (w)))
1606 ev_start (EV_A_ (W)w, 1);
1607 wlist_add ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
1611 ev_child_stop (EV_P_ struct ev_child *w)
1613 ev_clear_pending (EV_A_ (W)w);
1614 if (expect_false (!ev_is_active (w)))
1617 wlist_del ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
1618 ev_stop (EV_A_ (W)w);
1621 /*****************************************************************************/
1627 void (*cb)(int revents, void *arg);
1632 once_cb (EV_P_ struct ev_once *once, int revents)
1634 void (*cb)(int revents, void *arg) = once->cb;
1635 void *arg = once->arg;
1637 ev_io_stop (EV_A_ &once->io);
1638 ev_timer_stop (EV_A_ &once->to);
1645 once_cb_io (EV_P_ struct ev_io *w, int revents)
1647 once_cb (EV_A_ (struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
1651 once_cb_to (EV_P_ struct ev_timer *w, int revents)
1653 once_cb (EV_A_ (struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
1657 ev_once (EV_P_ int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
1659 struct ev_once *once = (struct ev_once *)ev_malloc (sizeof (struct ev_once));
1661 if (expect_false (!once))
1663 cb (EV_ERROR | EV_READ | EV_WRITE | EV_TIMEOUT, arg);
1670 ev_init (&once->io, once_cb_io);
1673 ev_io_set (&once->io, fd, events);
1674 ev_io_start (EV_A_ &once->io);
1677 ev_init (&once->to, once_cb_to);
1680 ev_timer_set (&once->to, timeout, 0.);
1681 ev_timer_start (EV_A_ &once->to);