+SIGHANDLERTYPE set_signal_handler(int sig, SIGHANDLERTYPE handler)
+/*
+ * This function is called by other parts of the program to
+ * setup the signal handler after a change to the signal context.
+ * This is done to improve robustness of the signal handling code.
+ * It has the same prototype as signal(2).
+ */
+{
+ SIGHANDLERTYPE rethandler;
+#ifdef HAVE_SIGACTION
+ struct sigaction sa_new, sa_old;
+
+ memset (&sa_new, 0, sizeof sa_new);
+ sigemptyset (&sa_new.sa_mask);
+ sa_new.sa_handler = handler;
+ sa_new.sa_flags = 0;
+#ifdef SA_RESTART /* SunOS 4.1 portability hack */
+ /* system call should restart on all signals except SIGALRM */
+ if (sig != SIGALRM)
+ sa_new.sa_flags |= SA_RESTART;
+#endif
+#ifdef SA_NOCLDSTOP /* SunOS 4.1 portability hack */
+ if (sig == SIGCHLD)
+ sa_new.sa_flags |= SA_NOCLDSTOP;
+#endif
+ sigaction(sig, &sa_new, &sa_old);
+ rethandler = sa_old.sa_handler;
+#if defined(SIGPWR)
+ if (sig == SIGCHLD)
+ sigaction(SIGPWR, &sa_new, NULL);
+#endif
+#else /* HAVE_SIGACTION */
+ rethandler = signal(sig, handler);
+#if defined(SIGPWR)
+ if (sig == SIGCHLD)
+ signal(SIGPWR, handler);
+#endif
+ /* system call should restart on all signals except SIGALRM */
+ siginterrupt(sig, sig == SIGALRM);
+#endif /* HAVE_SIGACTION */
+ return rethandler;
+}