+ if(sig) {
+ sig->cb(loop, sig->data);
+ }
+}
+
+static void pipe_init(event_loop_t *loop) {
+ if(!pipe(loop->pipefd)) {
+ io_add(loop, &loop->signalio, signalio_handler, NULL, loop->pipefd[0], IO_READ);
+ }
+}
+
+void signal_trigger(event_loop_t *loop, signal_t *sig) {
+
+ uint8_t signum = sig->signum;
+ write(loop->pipefd[1], &signum, 1);
+ return;
+
+}
+
+void signal_add(event_loop_t *loop, signal_t *sig, signal_cb_t cb, void *data, uint8_t signum) {
+ if(sig->cb) {
+ return;
+ }
+
+ sig->cb = cb;
+ sig->data = data;
+ sig->signum = signum;
+ sig->node.data = sig;
+
+ if(loop->pipefd[0] == -1) {
+ pipe_init(loop);
+ }
+
+ if(!splay_insert_node(&loop->signals, &sig->node)) {
+ abort();
+ }
+}
+
+void signal_del(event_loop_t *loop, signal_t *sig) {
+ if(!sig->cb) {
+ return;
+ }
+
+ loop->deletion = true;
+
+ splay_unlink_node(&loop->signals, &sig->node);
+ sig->cb = NULL;
+}
+
+void idle_set(event_loop_t *loop, idle_cb_t cb, void *data) {
+ loop->idle_cb = cb;
+ loop->idle_data = data;
+}
+
+bool event_loop_run(event_loop_t *loop, pthread_mutex_t *mutex) {
+ fd_set readable;
+ fd_set writable;
+
+ while(loop->running) {
+ gettimeofday(&loop->now, NULL);
+ struct timeval diff, it, *tv = NULL;
+
+ while(loop->timeouts.head) {
+ timeout_t *timeout = loop->timeouts.head->data;
+ timersub(&timeout->tv, &loop->now, &diff);
+
+ if(diff.tv_sec < 0) {
+ timeout->cb(loop, timeout->data);
+
+ if(timercmp(&timeout->tv, &loop->now, <)) {
+ timeout_del(loop, timeout);
+ }
+ } else {
+ tv = &diff;
+ break;
+ }
+ }
+
+ if(loop->idle_cb) {
+ it = loop->idle_cb(loop, loop->idle_data);
+
+ if(it.tv_sec >= 0 && (!tv || timercmp(&it, tv, <))) {
+ tv = ⁢
+ }
+ }
+
+ memcpy(&readable, &loop->readfds, sizeof(readable));
+ memcpy(&writable, &loop->writefds, sizeof(writable));
+
+ int fds = 0;
+
+ if(loop->ios.tail) {
+ io_t *last = loop->ios.tail->data;
+ fds = last->fd + 1;
+ }
+
+ // release mesh mutex during select
+ if(mutex) {
+ pthread_mutex_unlock(mutex);
+ }
+
+ int n = select(fds, &readable, &writable, NULL, tv);
+
+ if(mutex) {
+ pthread_mutex_lock(mutex);
+ }
+
+ if(n < 0) {
+ if(sockwouldblock(errno)) {
+ continue;
+ } else {
+ return false;
+ }
+ }
+
+ if(!n) {
+ continue;
+ }
+
+ // Normally, splay_each allows the current node to be deleted. However,
+ // it can be that one io callback triggers the deletion of another io,
+ // so we have to detect this and break the loop.
+
+ loop->deletion = false;
+
+ for splay_each(io_t, io, &loop->ios) {
+ if(FD_ISSET(io->fd, &writable) && io->cb) {
+ io->cb(loop, io->data, IO_WRITE);
+ }
+
+ if(loop->deletion) {
+ break;
+ }
+
+ if(FD_ISSET(io->fd, &readable) && io->cb) {
+ io->cb(loop, io->data, IO_READ);
+ }
+
+ if(loop->deletion) {
+ break;
+ }