How to gracefully shutdown emacs daemon?

Viewed 33818

On login to Ubuntu, I start an Emacs (version 23) daemon using Ubuntu's Startup programs. I then start Emacs clients whenever I need to edit something. When I logoff from Ubuntu, it says Emacs is still running, of course. I need to attach a script somewhere to tell Gnome to shutdown emacs when I logoff/shutdown.

1) What should the script look like? "kill-emacs" doesn't seem to work.

2) Where should I put this script? There's nothing in the startup programs (System->Sessions menu) panel that looks useful. I'd prefer something that works in the user's account, rather than hacking the PostSession script or something else with root access.

9 Answers

ShreevatsaR is right, the answer is kill-emacs or save-buffers-kill-emacs, both of which are interactive, and so can be run from within Emacs with M-x save-buffers-kill-emacs. This is probably the best way to do it, since you will get to save modified files.

Another alternative is to make a shell file like this:

#!/bin/bash
emacsclient -e "(kill-emacs)"

Which you can run from wherever you like (menu icon, panel, etc).

Another addendum to ShreevatsaR: the python script works like a charm, but I'd suggest using

emacsclient -e '(let ((last-nonmenu-event nil))(save-buffers-kill-emacs))'
as command. Setting last-nonmenu-event to nil forces emacs into mouse-mode, so you get "nice" dialog boxes instead of prompts in the minibuffer.

Or even more fancy (somewhere in your emacs config):

(defun shutdown-emacs-server () (interactive)
  (when (not (eq window-system 'x))
    (message "Initializing x windows system.")
    (x-initialize-window-system)
    (when (not x-display-name) (setq x-display-name (getenv "DISPLAY")))
    (select-frame (make-frame-on-display display '((window-system . x))))
  )
  (let ((last-nonmenu-event nil)(window-system "x"))(save-buffers-kill-emacs)))

and then:

emacsclient -e '(shutdown-emacs-server)'

you can put emacsclient -e "(kill-emacs)" in GDM's PostSession directory or directly in the Default script:

/etc/gdm/PostSession/Default

see also GDM documentation.

Related