+ if (argmatch (argv, argc, "-daemon", "--daemon", 5, NULL, &skip_args)
+ || argmatch (argv, argc, "-daemon", "--daemon", 5, &dname_arg, &skip_args))
+ {
+#ifndef DOS_NT
+ pid_t f;
+
+ /* Start as a daemon: fork a new child process which will run the
+ rest of the initialization code, then exit.
+
+ Detaching a daemon requires the following steps:
+ - fork
+ - setsid
+ - exit the parent
+ - close the tty file-descriptors
+
+ We only want to do the last 2 steps once the daemon is ready to
+ serve requests, i.e. after loading .emacs (initialization).
+ OTOH initialization may start subprocesses (e.g. ispell) and these
+ should be run from the proper process (the one that will end up
+ running as daemon) and with the proper "session id" in order for
+ them to keep working after detaching, so fork and setsid need to be
+ performed before initialization.
+
+ We want to avoid exiting before the server socket is ready, so
+ use a pipe for synchronization. The parent waits for the child
+ to close its end of the pipe (using `daemon-initialized')
+ before exiting. */
+ if (pipe (daemon_pipe) == -1)
+ {
+ fprintf (stderr, "Cannot pipe!\n");
+ exit (1);
+ }
+
+ f = fork ();
+ if (f > 0)
+ {
+ int retval;
+ char buf[1];
+
+ /* Close unused writing end of the pipe. */
+ close (daemon_pipe[1]);
+
+ /* Just wait for the child to close its end of the pipe. */
+ do
+ {
+ retval = read (daemon_pipe[0], &buf, 1);
+ }
+ while (retval == -1 && errno == EINTR);
+
+ if (retval < 0)
+ {
+ fprintf (stderr, "Error reading status from child\n");
+ exit (1);
+ }
+ else if (retval == 0)
+ {
+ fprintf (stderr, "Error: server did not start correctly\n");
+ exit (1);
+ }
+
+ close (daemon_pipe[0]);
+ exit (0);
+ }
+ if (f < 0)
+ {
+ fprintf (stderr, "Cannot fork!\n");
+ exit (1);
+ }
+
+ if (dname_arg)
+ daemon_name = xstrdup (dname_arg);
+ /* Close unused reading end of the pipe. */
+ close (daemon_pipe[0]);
+ /* Make sure that the used end of the pipe is closed on exec, so
+ that it is not accessible to programs started from .emacs. */
+ fcntl (daemon_pipe[1], F_SETFD, FD_CLOEXEC);
+
+#ifdef HAVE_SETSID
+ setsid();
+#endif
+#else /* DOS_NT */
+ fprintf (stderr, "This platform does not support the -daemon flag.\n");
+ exit (1);
+#endif /* DOS_NT */
+ }
+