Singleton Emacs Server

My .emacs file calls server-start so I can use emacsclient from the shell to send random editing jobs to emacs. However, with multiple emacs processes running, I sometimes have to hunt around for the emacs instance that emacsclient sent the editing job to do. Bummer!

I'd prefer emacsclient to send all my editing jobs to a single, known emacs process (unless I tell it to use another). The server-name variable can help with this. The server-name value, which defaults to "server", affects the name of the unix domain socket that emacs opens for emacsclient's use. The default socket file is "/tmp/emacs<user-uid>/server". The command "emacsclient -s <server-name>" uses the socket named <server-name> to send the editing job to the emacs process owning the socket. So it would seem that the following settings in your .emacs would do the trick:

(setq server-name "my-server") 
(start-server)

However, if you start another emacs process, it will clobber the existing socket file and subsequent emacsclient requests to "my-server" will go to the new process. Furthermore, emacs doesn't clean up the socket files on exit. This makes it tough to detect if a server with a particular server-name is running.

Below is a wrapper around server-start that helps. First, it allows you to easily name the server. Secondly, it arranges for emacs to delete the socket files it owns when emacs shuts down. This allows the function to use the existence of the socket file to decide if a server process exists for a given name -- so there is a way to refuse to start the server if an existing emacs process is already running it.

(require 'server)

(defun start-named-server (name)
  "Start a server named 'name' - ensure only 1 server of that name is running"
  (interactive "sServer Name: ")
  (setq server-name name)
  (setq mk-server-socket-file (concat server-socket-dir "/" name))
  (unless (file-exists-p mk-server-socket-file)
    (server-start)
    (add-hook 'kill-emacs-hook
              (lambda ()
                (when (file-exists-p mk-server-socket-file)
                  (delete-file mk-server-socket-file))))))

(start-named-server "server") ; default server-name

Additional emacs instances can start a server via "M-x start-named-server ENTER <server-name>".

Technorati tags for this post:

Comments on "Singleton Emacs Server":

Comment by AprilCoolsDay

Posted at Jul 22nd 2009.
What about the built-in function called server-running-p?

Comment by Matt

Posted at Jul 22nd 2009. Matt's URL
Good suggestion. That simplifies things as we don't have to check for the socket file.

And my current emacs (v23 built from CVS) manages to delete its socket file by itself -- so the kill-emacs-hook is probably unnecessary now.

Comment by mbt shoes

Posted at Jul 23rd 2010. mbt shoes's URL
Allowed html tags: br p blockquote i b em code strong u ol ul li a
(type "HuMaN" here)