+/* It is most convenient to handle the recheck timeout, as well as
+ * child death, in signal handlers. Our signals all block each other,
+ * and the main program has signals blocked except in sigsuspend, so
+ * we don't need to worry about async-signal-safety, or errno. */
+
+static struct stat baseline_time;
+static pid_t script_child, stage2_pgrp;
+static bool out_of_date;
+
+static void record_baseline_time(void) {
+ stab_mtimenow(&baseline_time);
+}
+
+static void become_pgrp(void) {
+ int r;
+
+ stage2_pgrp = getpid();
+
+ r = setpgid(0,0);
+ if (r) err(127,"(stage2) setpgid");
+}
+
+static void atexit_handler(void) {
+ int r;
+
+ sighandler_t sigr = signal(SIGTERM,SIG_IGN);
+ if (sigr == SIG_ERR) warn("(stage2) signal(SIGTERM,SIG_IGN)");
+
+ r = killpg(stage2_pgrp,SIGTERM);
+ if (r) warn("(stage) killpg failed");
+}
+
+static void alarm_handler(int dummy) {
+ if (out_of_date)
+ /* second timeout */
+ exit(0); /* transfers control to atexit_handler */
+
+ out_of_date = check_garbage_vs(&baseline_time);
+ queue_alarm();
+}
+
+static void child_handler(int dummy) {
+ for (;;) {
+ int status;
+ pid_t got = waitpid(-1, &status, WNOHANG);
+ if (got == (pid_t)-1) err(127,"(stage2) waitpid");
+ if (got != script_child) {
+ warn("(stage2) waitpid got status %d for unknown child [%lu]",
+ status, (unsigned long)got);
+ continue;
+ }
+ if (WIFEXITED(status)) {
+ int v = WEXITSTATUS(status);
+ if (v) warn("program failed with error exit status %d", v);
+ exit(status);
+ } else if (WIFSIGNALED(status)) {
+ int s = WTERMSIG(status);
+ err(status & 0xff, "program died due to fatal signal %s%s",
+ strsignal(s), WCOREDUMP(status) ? " (core dumped" : "");
+ } else {
+ err(127, "program failed with crazy wait status %#x", status);
+ }
+ }
+ exit(127);
+}
+
+static void setup_handlers(void) {
+ struct sigaction sa;
+ int r;
+
+ r = atexit(atexit_handler);
+ if (r) err(127,"(stage2) atexit");
+
+ sigemptyset(&sa.sa_mask);
+ sigaddset(&sa.sa_mask, SIGALRM);
+ sigaddset(&sa.sa_mask, SIGCHLD);
+ sa.sa_flags = 0;
+
+ r = sigprocmask(SIG_BLOCK, &sa.sa_mask, 0);
+ if (r) err(127,"(stage2) sigprocmask(SIG_BLOCK,)");
+
+ sa.sa_handler = alarm_handler;
+ r = sigaction(SIGALRM, &sa, 0);
+ if (r) err(127,"(stage2) sigaction SIGALRM");
+
+ sa.sa_flags |= SA_NOCLDSTOP;
+ sa.sa_handler = child_handler;
+ r = sigaction(SIGCHLD, &sa, 0);
+ if (r) err(127,"(stage2) sigaction SIGCHLD");
+}
+
+static void spawn_script(void) {
+ script_child = fork();
+ if (script_child == (pid_t)-1) err(127,"(stage2) fork");
+ if (!script_child) {
+ execlp(interp,
+ interp, script, (char*)0);
+ err(127,"(stage2) exec interpreter (`%s', for `%s')\n",interp,script);
+ }
+}
+
+static void queue_alarm(void) {
+ alarm(check_interval);
+}
+
+static void await_something(void) {
+ int r;
+ sigset_t mask;
+ sigemptyset(&mask);
+
+ for (;;) {
+ r = sigsuspend(&mask);
+ assert(r==-1);
+ if (errno != EINTR) err(127,"(stage2) sigsuspend");
+ }