+#include <sys/types.h>
+#include <sys/stat.h>
+
+pid_t citserver_pid;
+pid_t webcit_pid;
+pid_t webcits_pid;
+int shutting_down = 0;
+
+// Call this instead of exit() just for common diagnostics etc.
+void ctdlvisor_exit(int code) {
+ printf("ctdlvisor: exit code %d\n", code);
+ exit(code);
+}
+
+
+// Interrupting this program with a signal will begin an orderly shutdown.
+void signal_handler(int signal) {
+ fprintf(stderr, "ctdlvisor: caught signal %d\n", signal);
+
+ while(shutting_down) {
+ fprintf(stderr, "ctdlvisor: already shutting down\n");
+ sleep(1);
+ }
+
+ int status;
+ pid_t who_exited;
+ char *what_exited = NULL;
+
+ shutting_down = 1;
+ kill(citserver_pid, SIGTERM);
+ kill(webcit_pid, SIGTERM);
+ kill(webcits_pid, SIGTERM);
+ do {
+ fprintf(stderr, "ctdlvisor: waiting for all child process to exit...\n");
+ who_exited = waitpid(-1, &status, 0);
+ if (who_exited == citserver_pid) {
+ what_exited = "Citadel Server";
+ }
+ else if (who_exited == webcit_pid) {
+ what_exited = "WebCit HTTP";
+ }
+ else if (who_exited == webcits_pid) {
+ what_exited = "WebCit HTTPS";
+ }
+ else {
+ what_exited = "unknown";
+ }
+ if (who_exited >= 0) {
+ if (WIFEXITED(status)) {
+ fprintf(stderr, "ctdlvisor: %d (%s) exited, exitcode=%d\n", who_exited, what_exited, WEXITSTATUS(status));
+ }
+ else if (WIFSIGNALED(status)) {
+ fprintf(stderr, "ctdlvisor: %d (%s) crashed, signal=%d\n", who_exited, what_exited, WTERMSIG(status));
+ }
+ else {
+ fprintf(stderr, "ctdlvisor: %d (%s) ended, status=%d\n", who_exited, what_exited, status);
+ }
+ }
+ } while (who_exited >= 0);
+ ctdlvisor_exit(0);
+}
+
+
+void detach_from_tty(void) {
+ signal(SIGHUP, SIG_IGN);
+ signal(SIGINT, SIG_IGN);
+ signal(SIGQUIT, SIG_IGN);
+
+ setsid(); // become our own process group leader
+ umask(0);
+ if ( (freopen("/dev/null", "r", stdin) != stdin) ||
+ (freopen("/dev/null", "w", stdout) != stdout) ||
+ (freopen("/dev/null", "w", stderr) != stderr)
+ ) {
+ fprintf(stderr, "sysdep: unable to reopen stdio: %s\n", strerror(errno));
+ }
+}