+/*----------------------------------------------------------
+ | closeSession
+ | try to close everything before leaving
+ +--------------------------------------------------------- */
+static void closeSession (int status, void *data) {
+ /* AFB_session *session = data; */
+}
+
+/*----------------------------------------------------------
+ | timeout signalQuit
+ +--------------------------------------------------------- */
+void signalQuit (int signum)
+{
+ fprintf(stderr, "Terminating signal received %s\n", strsignal(signum));
+ exit(1);
+}
+
+
+/*----------------------------------------------------------
+ | Error signals
+ |
+ +--------------------------------------------------------- */
+__thread sigjmp_buf *error_handler;
+static void signalError(int signum)
+{
+ sigset_t sigset;
+
+ // unlock signal to allow a new signal to come
+ if (error_handler != NULL) {
+ sigemptyset(&sigset);
+ sigaddset(&sigset, signum);
+ sigprocmask(SIG_UNBLOCK, &sigset, 0);
+ longjmp(*error_handler, signum);
+ }
+ if (signum == SIGALRM)
+ return;
+ fprintf(stderr, "Unmonitored signal received %s\n", strsignal(signum));
+ exit(2);
+}
+
+static void install_error_handlers()
+{
+ int i, signals[] = { SIGALRM, SIGSEGV, SIGFPE, 0 };
+
+ for (i = 0; signals[i] != 0; i++) {
+ if (signal(signals[i], signalError) == SIG_ERR) {
+ fprintf(stderr, "Signal handler error\n");
+ exit(1);
+ }
+ }
+}
+
+/*----------------------------------------------------------
+ | daemonize
+ | set the process in background
+ +--------------------------------------------------------- */
+static void daemonize(AFB_session *session)
+{
+ int consoleFD;
+ int pid;
+
+ // open /dev/console to redirect output messAFBes
+ consoleFD = open(session->config->console, O_WRONLY | O_APPEND | O_CREAT , 0640);
+ if (consoleFD < 0) {
+ fprintf (stderr,"\nERR: AFB-daemon cannot open /dev/console (use --foreground)\n\n");
+ exit (1);
+ }
+
+ // fork process when running background mode
+ pid = fork ();
+
+ // if fail nothing much to do
+ if (pid == -1) {
+ fprintf (stderr,"\nERR: AFB-daemon Failed to fork son process\n\n");
+ exit (1);
+ }
+
+ // if in father process, just leave
+ if (pid != 0) _exit (0);
+
+ // son process get all data in standalone mode
+ printf ("\nAFB: background mode [pid:%d console:%s]\n", getpid(),session->config->console);
+
+ // redirect default I/O on console
+ close (2); dup(consoleFD); // redirect stderr
+ close (1); dup(consoleFD); // redirect stdout
+ close (0); // no need for stdin
+ close (consoleFD);
+
+#if 0
+ setsid(); // allow father process to fully exit
+ sleep (2); // allow main to leave and release port
+#endif
+
+ fprintf (stderr, "----------------------------\n");
+ fprintf (stderr, "INF: main background pid=%d\n", getpid());
+ fflush (stderr);
+}
+