packages feed

nova-nix-0.11.0.0 / test / cbits / process_wait.c

/* * The end of a process the test is not the parent of: a process a build * left behind, which a build user's kill or a stopped build's kill is to * end, is waited for through what refers to it, a pidfd on Linux and a * kqueue process filter on macOS, rather than looked at once or polled. */#if defined(__APPLE__)#define _DARWIN_C_SOURCE#else#define _GNU_SOURCE#endif#include <errno.h>#if defined(__linux__)#include <poll.h>#include <sys/syscall.h>#include <unistd.h>#elif defined(__APPLE__)#include <stdint.h>#include <sys/event.h>#include <sys/time.h>#include <sys/types.h>#include <time.h>#include <unistd.h>#endif/* Wait up to TIMEOUT_MS milliseconds for the process PID to end.  Answers * 0 once it has ended or when there is no such process, 1 when it is * still running at the timeout, or -1 with errno set, ENOSYS where the * system has no way to watch a process. */int nova_test_await_exit(int pid, int timeout_ms){#if defined(__linux__) && defined(SYS_pidfd_open)    struct pollfd watched;    int ready;    int fd = (int)syscall(SYS_pidfd_open, pid, 0);    if (fd < 0)        return errno == ESRCH ? 0 : -1;    watched.fd = fd;    watched.events = POLLIN;    watched.revents = 0;    do {        ready = poll(&watched, 1, timeout_ms);    } while (ready < 0 && errno == EINTR);    close(fd);    if (ready < 0)        return -1;    return ready == 0 ? 1 : 0;#elif defined(__APPLE__)    struct kevent change;    struct kevent event;    struct timespec limit;    int queue;    int ready;    int saved;    queue = kqueue();    if (queue < 0)        return -1;    EV_SET(&change, (uintptr_t)pid, EVFILT_PROC, EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, NULL);    limit.tv_sec = timeout_ms / 1000;    limit.tv_nsec = (long)(timeout_ms % 1000) * 1000000L;    /* A process already gone cannot be watched, and has ended. */    if (kevent(queue, &change, 1, NULL, 0, NULL) < 0) {        saved = errno;        close(queue);        errno = saved;        return saved == ESRCH ? 0 : -1;    }    do {        ready = kevent(queue, NULL, 0, &event, 1, &limit);    } while (ready < 0 && errno == EINTR);    saved = errno;    close(queue);    errno = saved;    if (ready < 0)        return -1;    return ready == 0 ? 1 : 0;#else    (void)pid;    (void)timeout_ms;    errno = ENOSYS;    return -1;#endif}