Subject: Re: bug#1058: 23.0.60; emacs --daemon should not return until socket is ready

From: Dan Nicolaescu <[email-masked]>
Date: Thu, 2 Oct 2008 11:40:24 -0700 (PDT)

Romain Francoise <[email-masked]> writes:

  > Here's version one of a patch for this, please let me know what you
  > think.

Looks good to me (assuming it works), I found some nits:

  > @@ -1224,7 +1224,8 @@ opening the first frame (e.g. open a connection to an X server).")
  >    ;; processing all command line arguments to allow e.g. `server-name'
  >    ;; to be changed before the server starts.
  >    (when (daemonp)
  > -    (server-start))
  > +    (server-start)
  > +    (daemon-initialized))

Maybe "notify-daemon-initialized"?

  >    ;; Run emacs-session-restore (session management) if started by
  >    ;; the session manager and we have a session manager connection.
  > diff --git a/src/emacs.c b/src/emacs.c
  > index f94d2d3..d4d16b7 100644
  > --- a/src/emacs.c
  > +++ b/src/emacs.c
  > @@ -235,6 +235,13 @@ int noninteractive1;
  >  /* Nonzero means Emacs was started as a daemon.  */
  >  int is_daemon = 0;
  >  
  > +/* Set nonzero after the daemon has finished initializing.  */
  > +int daemon_initialized = 0;

Make it a static inside the only user?

  > +/* Pipe used to send exit notification to the daemon parent at
  > +   startup.  */
  > +int daemon_pipe[2];
  > +
  >  /* Save argv and argc.  */
  >  char **initial_argv;
  >  int initial_argc;
  > @@ -1074,16 +1081,56 @@ main (int argc, char **argv)
  >    if (argmatch (argv, argc, "-daemon", "--daemon", 5, NULL, &skip_args))
  >      {
  >  #ifndef DOS_NT
  > -      pid_t f = fork ();
  > +      pid_t f;
  >        int nfd;
  > +
  > +      /* Start as a daemon: fork a new child process which will run the
  > +	 rest of the initialization code, then exit.

The child runs everything, not only the initialization.  
Maybe say "exit in order to detach from the terminal" or some such?

  > +DEFUN ("daemon-initialized", Fdaemon_initialized, Sdaemon_initialized, 0, 0, 0,
  > +       doc: /* Mark the Emacs daemon as being initialized.  */)
  > +  ()
  > +{
  > +  if (is_daemon)
  > +    {
  > +      if (! daemon_initialized)
  > +	{
  > +	  /* Closing the pipe will notify the parent that it can exit. */
  > +	  close (daemon_pipe[1]);
  > +	  daemon_initialized = 1;
  > +	}

       else error ("Can only do this once");

BTW, ideally the parent would exit when it detects that the server is
started, but that's much more complicated to implement...