The brewpanel can now run in daemon mode or debug mode.

Wed, 25 Nov 2015 15:48:01 +0100

author
Michiel Broek <mbroek@mbse.eu>
date
Wed, 25 Nov 2015 15:48:01 +0100
changeset 432
332daf75352e
parent 431
b3895cd6edd3
child 433
1421ece29197

The brewpanel can now run in daemon mode or debug mode.

brewpanel/brewpanel.c file | annotate | diff | comparison | revisions
--- a/brewpanel/brewpanel.c	Wed Nov 25 15:30:28 2015 +0100
+++ b/brewpanel/brewpanel.c	Wed Nov 25 15:48:01 2015 +0100
@@ -27,6 +27,7 @@
 #ifdef HAVE_SDL_SDL_H
 
 int			debug = FALSE;			/* Console debugging		*/
+static pid_t		pgrp, mypid;
 int			my_shutdown = FALSE;		/* Shutdown requested		*/
 char			*Paneltype = NULL;		/* Panel to emulate		*/
 int			PAN_x;				/* Screen X size		*/
@@ -38,6 +39,8 @@
 SDL_Surface		*PAN_surface = NULL;		/* Main surface			*/
 
 
+int server(void);
+
 void help(void)
 {
     fprintf(stdout, "Usage: brewpanel [-d] [-h] [-p <paneltype>]\n");
@@ -71,9 +74,8 @@
 
 int main(int argc, char *argv[])
 {
-    int		i, rc = 0, c, max_x = 0, max_y = 0;
-    SDL_Rect	**modes;
-    char	title[81];
+    int		i, c, rc = 0;
+    pid_t	frk;
 
     Paneltype = calloc(128, sizeof(char));
 
@@ -115,6 +117,67 @@
 	    signal(i, (void (*))die);
     }
 
+    if (debug) {
+	/*
+	 * Run in foreground when debugging
+	 */
+    	rc = server();
+    } else {
+	/*
+	 * Fork the daemon
+	 */
+	if ((pgrp = setpgid(0, 0)) == -1) {
+	    syslog(LOG_NOTICE, "setpgpid failed");
+	}
+
+	frk = fork();
+	switch (frk) {
+	    case -1:
+		    	syslog(LOG_NOTICE, "Daemon fork failed: %s", strerror(errno));
+			exit(1);
+	    case 0:	/*
+			 * Run the daemon
+			 */
+			fclose(stdin);
+			if (open("/dev/null", O_RDONLY) != 0) {
+			    syslog(LOG_NOTICE, "Reopen of stdin to /dev/null failed");
+			    _exit(2);
+			}
+			fclose(stdout);
+			if (open("/dev/null", O_WRONLY | O_APPEND | O_CREAT,0600) != 1) {
+			    syslog(LOG_NOTICE, "Reopen of stdout to /dev/null failed");
+			    _exit(2);
+			}
+			fclose(stderr);
+			if (open("/dev/null", O_WRONLY | O_APPEND | O_CREAT,0600) != 2) {
+			    syslog(LOG_NOTICE, "Reopen of stderr to /dev/null failed");
+			    _exit(2);
+			}
+			mypid = getpid();
+			rc = server();
+			break;
+			/* Not reached */
+	    default:
+			/*
+			 * Here we detach this process and let the child
+			 * run the deamon process.
+			 */
+			syslog(LOG_NOTICE, "Starting daemon with pid %d", frk);
+			exit(0);
+	}
+    }
+
+    syslog(LOG_NOTICE, "Finished, rc=%d", rc);
+    return rc;
+}
+
+
+int server(void)
+{
+    int         max_x = 0, max_y = 0;
+    SDL_Rect    **modes;
+    char        title[81];
+
     /* 
      * Initialize defaults, Video and Audio
      */
@@ -162,7 +225,6 @@
     SDL_FreeSurface(PAN_surface);
     SDL_Quit();
 
-    syslog(LOG_NOTICE, "Finished, rc=%d", rc);
     return 0;
 }
 

mercurial