#include "signal.h"
#include <signal.h>
#include <syslog.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

static Sigfunc * my_signal(int signo, Sigfunc * func) {
  struct sigaction act, oact;

  if (func==NULL)
    return NULL;

  act.sa_handler = func;
  sigemptyset(&act.sa_mask);
  act.sa_flags = 0;
  if (signo == SIGALRM) {
#ifdef SA_INTERRUPT
    /* Linux header says "historical no-op." 
     * BSD doesn't have it. So it can't be _that_
     * important. */
    act.sa_flags |= SA_INTERRUPT;
#endif
  } else {
    act.sa_flags |= SA_RESTART;
  }
  if (sigaction(signo,&act,&oact) < 0)
    return SIG_ERR;
  return oact.sa_handler;
}

Sigfunc * Signal(int signo, Sigfunc * func) {
  Sigfunc * sigfunc;

  if (func==NULL)
    return NULL;
  if ((sigfunc = my_signal(signo, func)) == SIG_ERR) {
    syslog(LOG_ERR,"%s: %s","failed to set signal handler",strerror(errno));
    perror("Signal error");
  }
  return sigfunc;
}
