5

The general case:
Simply put, given that I start two processes (Aand B) with, e.g., async-start-process, what is best way of killing B if A terminates?

My specific usecase:
I'm debugging embedded software on an external chip and launch a GDB server that interfaces the chip and GDB like this (gdb ... "-ex \"target remote ...\"") and I want to kill the GDB server process when GDB quits.

Additional edit: It would be nice to be able to kill the GDB server when quitting GDB, though. I.e., the opposite way around: hitting q in the GDB buffer would shut everything down.

I tried searching through the Emacs/elisp documentation, but I'm pretty new to elisp :) Any suggestions?

thomsten
  • 53
  • 3
  • You even have a `finish-func` with `async-start-process`. You can use that one to kill `B` with `kill-process` when `A` finishes. – Tobias Apr 06 '17 at 12:20
  • Good point, thanks :) It would be nice to be able to kill the GDB server when quitting GDB, though. I.e., the opposite way around: hitting `q` in the GDB buffer would shut everything down. – thomsten Apr 06 '17 at 12:57
  • As I understand your last comment you want the processes to mutually kill each other. This is an extension of your original question. Please add the comment to your question such that my answer addresses really the question and not a combination of a question with an additional comment. Thanks in advance. – Tobias Apr 06 '17 at 13:51

1 Answers1

5

For two processes A and B mutually killing each other you can use the following approach:

  1. Start the first process just with start-process and remember its process (as lisp object).
  2. Start the second process B with async-start-process and kill A in its finish-func.
  3. Define a process sentinel for A which kills B at exit of A.

Running example:

(defun make-kill-other-proc-sentinel (other-proc)
  "Create a process-sentinel killing other-proc when called."
  (assert (processp other-proc))
  `(lambda (proc &optional msg)
     (when (eq 'exit (process-status proc))
       (unless (eq 'exit (process-status ,other-proc))
     (kill-process ,other-proc)))))

(let* ((proc1 (start-process "*A*" "*A*" "xterm" "-T" "A"))
       (proc2 (async-start-process "*B*" "xterm" (make-kill-other-proc-sentinel proc1) "-T" "B")))
  (if (eq 'exit (process-status proc1))
      (kill-process proc2)
    (set-process-sentinel proc1 (make-kill-other-proc-sentinel proc2))))
Tobias
  • 32,569
  • 1
  • 34
  • 75