+void daemonize () {
+ const char *devnull = "/dev/null";
+
+ /* Fork once to ensure we aren't the process group leader */
+ int i = fork ();
+ if (i < 0) {
+ fprintf (stderr, "Unable to fork\n");
+ _exit (1);
+ }
+
+ /* Exit if we are the parent */
+ if (i > 0)
+ _exit (0); /* parent exits */
+
+ /* Start a new session */
+ setsid ();
+
+ /* Fork again so the session group leader exits */
+ i = fork ();
+ if (i < 0) {
+ fprintf (stderr, "Unable to fork\n");
+ _exit (1);
+ }
+
+ /* Exit if we are the parent */
+ if (i > 0)
+ _exit (0); /* parent exits */
+
+ if (chdir ("/") <0) {
+ fprintf (stderr, "Unable to chdir /\n");
+ _exit (1);
+ }
+
+ /* Now close all FDs and reopen the 3 stdxxx to /dev/null */
+ for (i = getdtablesize () - 1; i >= 0; i--)
+ close (i);
+
+ i = open (devnull, O_RDWR);
+ if (i == -1) {
+ fprintf (stderr, "Unable to open /dev/null\n");
+ _exit (1);
+ }
+ i = open (devnull, O_RDONLY);
+ if (i != 0) {
+ dup2 (i, 0);
+ close (i);
+ }
+ i = open (devnull, O_WRONLY);
+ if (i != 1) {
+ dup2 (i, 1);
+ close (i);
+ }
+ i = open (devnull, O_WRONLY);
+ if (i != 2) {
+ dup2 (i, 2);
+ close (i);
+ }
+}
+
+
+