//-----------------------------------------------------------------------------
// Copyright (c) 1994,1995 Southeastern Universities Research Association,
//                         Continuous Electron Beam Accelerator Facility
//
// This software was developed under a United States Government license
// described in the NOTICE file included as part of this distribution.
//
//-----------------------------------------------------------------------------
//
// Description:
//      Implemenation of signal handler
//
// Author:  
//      Jie Chen
//
// Revision History:
//   rsvcSignal.cc,v
// Revision 1.5  1998/03/19  18:31:01  chen
// add monitorEntry capability to server table
//
// Revision 1.4  1998/03/06  13:37:41  chen
// Use exit to quit
//
// Revision 1.3  1998/02/26  19:17:25  chen
// change exit to set rsvc_finished = 1
//
// Revision 1.2  1998/02/11  18:46:46  akers
// Ongoing development
//
// Revision 1.1  1998/01/22  17:08:21  akers
// Addition of new NameServer
//
//
//
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include "rsvcSignal.h"

#if defined (__linux)

#ifndef SIGSYS
#define SIGSYS SIGUNUSED
#endif

#endif

#ifdef _WIN32
int rsvcSignal::signals[] = 
{SIGINT, SIGILL, SIGFPE, SIGSEGV,
 SIGTERM, SIGABRT, SIGBREAK};

int rsvcSignal::numSignals = 7;

int
rsvcSignal::registerSignalHandlers (void)
{
  for (int i = 0; i < rsvcSignal::numSignals; i++) 
    if (signal (rsvcSignal::signals[i], rsvcSignal::signalFunc) < 0)
      return -1;
  
  return 0;
}

void
rsvcSignal::signalFunc (int signo)
{
  fprintf (stderr, "Interrupted by %d signal\n", signo);
  exit (1);
}

#else
int rsvcSignal::signals[] = 
{SIGINT, SIGQUIT, SIGILL, SIGFPE,
 SIGSYS, SIGPIPE, SIGBUS, SIGSEGV,
 SIGTERM, SIGIO, SIGHUP, SIGPOLL};

int rsvcSignal::numSignals = 12;

int
rsvcSignal::registerSignalHandlers (void)
{
  struct sigaction act, oact;

  act.sa_handler = &(rsvcSignal::signalFunc);
  sigemptyset (&act.sa_mask);
  act.sa_flags = 0;

  for (int i = 0; i < rsvcSignal::numSignals; i++) 
    if (sigaction (rsvcSignal::signals[i], &act, &oact) < 0)
      return -1;
  
  return 0;
}

void
rsvcSignal::signalFunc (int signo)
{
#ifdef sun
  char signame[SIG2STR_MAX];
  if (sig2str (signo, signame) == -1)
    sprintf (signame, "unknown");

  fprintf (stderr, "Interrupted by %s signal\n", signame);

  if (signo == SIGSEGV || signo == SIGBUS) {
    fprintf (stderr, "Fatal: Caught signal %s, Quit.......\n", signame);
    abort ();
  }
  else if (signo != SIGPIPE && signo != SIGTSTP &&
	   signo != SIGCONT && signo != SIGHUP) {
    exit (1);
  }
#else
  fprintf (stderr, "Interrupted by %d signal\n", signo);

  if (signo == SIGSEGV || signo == SIGBUS) {
    fprintf (stderr, "Fatal: Caught signal %d, Quit.......\n", signo);
    abort ();
  }
  else if (signo != SIGPIPE && signo != SIGTSTP &&
	   signo != SIGCONT && signo != SIGHUP) {
    // rsvc_finished = 1;
    exit (1);
  }
#endif
}
#endif

