Don’t fear the reaper

#include <stdio.h>
#include <signal.h>

/* Total idle timeout before sending signal to parent */
#define TIMEOUT 120

/* Verbose debugging output */
#define VERBOSE 1

static unsigned int idle_time = 0;

static void sig_handler(int sig) {
  switch(sig) {
  case SIGALRM:
    idle_time += 1;
    break;
  case SIGUSR1:
    idle_time = 0;
    break;
  }
}

int main(int argc, char **argv) {
  pid_t parent = (pid_t) 0;
  int remaining;

  parent = getppid();
#if VERBOSE
  pid_t my_pid = getpid();
  fprintf(stderr,
          "[%d] Waiting %d seconds to kill PID %d...\n",
          (int) my_pid, TIMEOUT, (int) parent);
#endif

  signal(SIGUSR1, sig_handler);
  signal(SIGALRM, sig_handler);

  while(1) {
    alarm(1);
    remaining = TIMEOUT - idle_time;
    if (remaining <= 0) {
      kill(parent, SIGINT);
#if VERBOSE
      fprintf(stderr, "Boom!\n");
#endif
      break;
    } else {
      pause();
#if VERBOSE
      if (remaining % 10 == 0) {
        fprintf(stderr, "  (reaper) %d seconds remaining\n", remaining);
      }
#endif
    }
  }

  return 0;
}

0 Responses to “Don’t fear the reaper”


  1. No Comments

Leave a Reply