/*
 *  $Id: signal.c,v 1.4 1997/11/06 00:20:14 yonah Exp $
 *
 *  signal handlers
 *  (part of diswww, a Discuss->WWW gateway)
 */

#ifndef lint
static char rcsid_signal[] = "$Id: signal.c,v 1.4 1997/11/06 00:20:14 yonah Exp $";
#endif

#include "proto.h"  /* the copyright notice is included in this file, too. */
#include "extern.h"
#include <signal.h>
#include <sys/wait.h>

/*** SIGNAL HANDLERS ***/

/*
 *  print a notice and exit
 */
void sig_exit(sig)
int sig;
{
  SYSLOG(LOG_NOTICE,"caught signal %d, exiting", sig);
  exit(10);
}

/*
 *  remove zombie children
 */
void sig_child(sig)
int sig;
{
  int pid, stat, z;
  while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
#ifdef DEBUG
  {
    if (WIFEXITED(stat)) {
      if ((z = WEXITSTATUS(stat)) != 0)
	SYSLOG(LOG_DEBUG,"child %d exited with status %d", pid, z);
    } else if (WIFSIGNALED(stat))
      SYSLOG(LOG_DEBUG,"child %d terminated by signal %d", pid,WTERMSIG(stat));
    else
      SYSLOG(LOG_DEBUG,"child %d did something weird (%x)", pid, stat);
  }
#endif
  ;
}
/*** **************** ***/

/*
 *  install signal handlers
 */
void deal_with_signals(void)
{
#ifdef POSIX_SOURCE
  struct sigaction sa;
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = SA_RESTART;
  sa.sa_handler = sig_exit;
  sigaction(SIGHUP, &sa, (struct sigaction *)0);
  sigaction(SIGINT, &sa, (struct sigaction *)0);
  sigaction(SIGTERM, &sa, (struct sigaction *)0);
  sa.sa_handler = sig_child;
  sigaction(SIGCHLD, &sa, (struct sigaction *)0);
#else
  signal(SIGHUP, sig_exit);
  signal(SIGINT, sig_exit);
  signal(SIGTERM, sig_exit);
  signal(SIGCHLD, sig_child);
#endif
}

