+ if(!splay_insert_node(&signal_tree, &sig->node))
+ abort();
+}
+
+void signal_del(signal_t *sig) {
+ if(!sig->cb)
+ return;
+
+ signal(sig->signum, SIG_DFL);
+
+ splay_unlink_node(&signal_tree, &sig->node);
+ sig->cb = NULL;
+}
+#endif
+
+bool event_loop(void) {
+ running = true;
+
+ fd_set readable;
+ fd_set writable;
+
+ while(running) {
+ gettimeofday(&now, NULL);
+ struct timeval diff, *tv = NULL;
+
+ while(timeout_tree.head) {
+ timeout_t *timeout = timeout_tree.head->data;
+ timersub(&timeout->tv, &now, &diff);
+
+ if(diff.tv_sec < 0) {
+ timeout->cb(timeout->data);
+ if(timercmp(&timeout->tv, &now, <))
+ timeout_del(timeout);
+ } else {
+ tv = &diff;
+ break;
+ }
+ }
+
+ memcpy(&readable, &readfds, sizeof readable);
+ memcpy(&writable, &writefds, sizeof writable);
+
+ int fds = 0;
+
+ if(io_tree.tail) {
+ io_t *last = io_tree.tail->data;
+ fds = last->fd + 1;
+ }
+
+#ifdef HAVE_MINGW
+ LeaveCriticalSection(&mutex);
+#endif
+ int n = select(fds, &readable, &writable, NULL, tv);
+#ifdef HAVE_MINGW
+ EnterCriticalSection(&mutex);
+#endif
+
+ if(n < 0) {
+ if(sockwouldblock(sockerrno))
+ continue;
+ else
+ return false;
+ }
+
+ if(!n)
+ continue;
+
+ for splay_each(io_t, io, &io_tree) {
+ if(FD_ISSET(io->fd, &writable))
+ io->cb(io->data, IO_WRITE);
+ else if(FD_ISSET(io->fd, &readable))
+ io->cb(io->data, IO_READ);