4

From what I have read, one way to speed up the emacs startup is to run emacs --daemon on login and then open files using emacslient instead of emacs, which will access the running emacs server instead of creating a new emacs instance.

However, I prefer to not put proframs in my autostart unless absolutely necessary, as a way yo speed up the login process. Is there a robust way to detect if an emacs server is running? This would let me write a simple script that would spawn the emacs server the first time I open a file with emacs.

#!/bin/sh
if emacs_daemon_is_not_running # <-- How do I do this?
then
    emacs --daemon
fi
emacsclient -c "$@"
9

You shouldn't even need to test if emacs is already running or not. emacsclient can start the emacs daemon if it's not already running. From emacsclient(1):

   -a, --alternate-editor=EDITOR
          if the Emacs server is not running,  run  the  specified  editor
          instead.   This can also be specified via the `ALTERNATE_EDITOR'
          environment variable.  If the  value  of  EDITOR  is  the  empty
          string,  run `emacs --daemon' to start Emacs in daemon mode, and
          try to connect to it.

I use an alias, ge, for editing files, defined like this:

alias ge="emacsclient -c -n --alternate-editor=\"\""
  • For fractionally greater readability on that alias, it suffices to replace the \"\" with a space. Alternatively, set the ALTERNATE_EDITOR environment variable (in a shell rc file, or if necessary in desktop environment settings), but set it blank, and then omit the --alternate-editor= part altogether. emacsclient respects the difference between set-but-empty (where it invokes the daemon) and unset (where it fails). – Darael Mar 14 '17 at 21:18
4

You can use emacsclient itself to test if there is a connection:

#!/bin/sh
if ! emacsclient -e 0 >&/dev/null
then emacs --daemon
fi
emacsclient -c "$@"

-e 0 means evaluate the expression "0", which just prints 0. The return code is non-zero if emacsclient fails to connect to the server.

  • Thanks. This is exactly the sort of thing I was looking for. – hugomg Oct 21 '15 at 17:59
1

You can put this in a shell function or script:

if ! ps h -o pid,args -C emacs | grep -q -- --daemon ; then
    emacs --daemon
fi
emacsclient -c "$@"

This assumes you are using the ps from the standard linux procps package. If you are using another ps, the exact options will be different.

  • I went with ps -e -o args | grep -q -- '^emacs --daemon$'. It seemed simpler and more reliable. – hugomg Oct 21 '15 at 2:25
  • yeah, the pid isn't needed - i only put it in there out of habit. ps -C emacs, however, is more reliable than ps -e | grep '^emacs' – cas Oct 21 '15 at 2:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.