Skip to content
suit Artifact [0492c3bb59]
Login

Artifact [0492c3bb59]

Artifact 0492c3bb59fbec48fcbb40194b9d77bcd0cdb4256b8c5d7acae36e92473e19a4:


// deadline SECONDS CMD [ARGS...]: run CMD in a session of its own. A
// watchdog process, outside that session and holding none of its files,
// kills the whole session SECONDS later (at most 900), even if deadline
// itself has been killed; it leaves as soon as the session is empty. If
// DEADLINE_PIDFILE is set, the session id is written there, for
// "kill -- -ID". A test helper for test/https.sh, not part of suit.
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

static bool gone(pid_t c)
{
    return kill(c, 0) < 0 && errno == ESRCH && kill(-c, 0) < 0 && errno == ESRCH;
}

int main(int argc, char **argv)
{
    if (argc < 3) {
        fprintf(stderr, "usage: deadline SECONDS CMD [ARGS...]\n");
        return 2;
    }
    long secs = strtol(argv[1], NULL, 10);
    if (secs < 1 || secs > 900) {
        fprintf(stderr, "deadline: 1 to 900 seconds\n");
        return 2;
    }
    pid_t c = fork();
    if (c < 0) {
        perror("deadline: fork");
        return 2;
    }
    if (c == 0) {
        if (setsid() < 0) {
            perror("deadline: setsid");
            _exit(2);
        }
        execvp(argv[2], argv + 2);
        perror("deadline: exec");
        _exit(127);
    }
    const char *pf = getenv("DEADLINE_PIDFILE");
    if (pf != NULL) {
        FILE *f = fopen(pf, "w");
        if (f != NULL) {
            fprintf(f, "%d\n", (int)c);
            fclose(f);
        }
    }
    pid_t w = fork();
    if (w < 0) {
        perror("deadline: fork");
        kill(-c, SIGKILL);
        return 2;
    }
    if (w == 0) {
        // The watchdog: a session of its own, so killing CMD's group spares it,
        // and no descriptor of the caller's, so it holds no pipe open.
        (void)setsid();
        int nul = open("/dev/null", O_RDWR);
        for (int fd = 0; fd < 3; fd++) dup2(nul, fd);
        for (int fd = 3; fd < 1024; fd++) close(fd);
        for (long i = 0; i < secs; i++) {
            sleep(1);
            if (gone(c)) _exit(0);
        }
        kill(-c, SIGTERM);
        sleep(2);
        kill(-c, SIGKILL);
        kill(c, SIGKILL);
        _exit(0);
    }
    int st = 0;
    while (waitpid(c, &st, 0) < 0) {
        if (errno != EINTR) return 2;
    }
    return WIFEXITED(st) ? WEXITSTATUS(st) : 128 + WTERMSIG(st);
}