#if defined(__APPLE__)#define _DARWIN_C_SOURCE#elif !defined(_WIN32)#define _POSIX_C_SOURCE 200809L#endif#include "nn_hangup.h"#include <errno.h>#if defined(__APPLE__)#include <stdint.h>#include <sys/event.h>#include <sys/types.h>#include <unistd.h>/* Wait on a queue watching both descriptors until one reports the end * of its file: 1 for the watched socket, 0 for the pipe, -1 on failure. */static int wait_for_eof(int queue, int watch_fd) { struct kevent event; int count; for (;;) { count = kevent(queue, NULL, 0, &event, 1, NULL); if (count < 0) { if (errno == EINTR) { continue; } return -1; } if (count > 0 && (event.flags & EV_ERROR) != 0) { errno = (int)event.data; return -1; } if (count > 0 && (event.flags & EV_EOF) != 0) { return event.ident == (uintptr_t)watch_fd ? 1 : 0; } }}/* Both descriptors are watched with the read filter, which reports EV_EOF * when the peer of a socket closes and when a pipe's last writer does; * EV_CLEAR keeps a socket the client still sends on from waking the loop * more than once per arrival. */int nn_wait_hangup(int watch_fd, int notify_fd) { struct kevent changes[2]; int queue; int answer; int saved; queue = kqueue(); if (queue < 0) { return -1; } EV_SET(&changes[0], (uintptr_t)watch_fd, EVFILT_READ, EV_ADD | EV_ENABLE | EV_CLEAR, 0, 0, NULL); EV_SET(&changes[1], (uintptr_t)notify_fd, EVFILT_READ, EV_ADD | EV_ENABLE | EV_CLEAR, 0, 0, NULL); answer = kevent(queue, changes, 2, NULL, 0, NULL) < 0 ? -1 : wait_for_eof(queue, watch_fd); saved = errno; (void)close(queue); errno = saved; return answer;}#elif !defined(_WIN32)#include <poll.h>/* POSIX reports POLLHUP whatever events are asked for, so none are, and a * client sending its next request does not wake the loop. A descriptor * that is not open is reported as POLLNVAL, which would never clear, so it * ends the wait as an error. */int nn_wait_hangup(int watch_fd, int notify_fd) { struct pollfd fds[2]; for (;;) { fds[0].fd = watch_fd; fds[0].events = 0; fds[0].revents = 0; fds[1].fd = notify_fd; fds[1].events = 0; fds[1].revents = 0; if (poll(fds, 2, -1) < 0) { if (errno == EINTR || errno == EAGAIN) { continue; } return -1; } if ((fds[0].revents & POLLNVAL) != 0 || (fds[1].revents & POLLNVAL) != 0) { errno = EBADF; return -1; } if ((fds[0].revents & POLLHUP) != 0) { return 1; } if ((fds[1].revents & POLLHUP) != 0) { return 0; } }}#else /* _WIN32 *//* The daemon on Windows serves a named pipe, which does not use this wait. */int nn_wait_hangup(int watch_fd, int notify_fd) { (void)watch_fd; (void)notify_fd; errno = ENOSYS; return -1;}#endif