by shigemk2

当面は技術的なことしか書かない

番兵

非同期プロセス終了時に処理を行わせるには「番兵(番人)」を使う。

;; 終了ステータスによる状態文字列を得る
(defun exit-status-test (n)
  (lexical-let (status)
    (set-process-sentinel
     (start-process "test" nil "ruby" "-e" (format "exit %d" n))
     (lambda (proc msg) (setq status msg)))
    (sit-for 0.3)
    status))
(exit-status-test 0)			; => "finished\n"
(exit-status-test 1)			; => "exited abnormally with code 1\n"
;; シグナルによる状態文字列を得る
(defun kill-test (func)
  (lexical-let (status)
    (setq sentinel (set-process-sentinel
		    (funcall func (prog1 (start-process "test" nil "ruby" "-e" "sleep 2")
				    (sit-for 0.1)))
		    (lambda (proc msg) (setq status msg))))
    (sit-for 0.3)
    status))
(kill-test 'kill-process)		; => "killed: 9\n"
(ignore-errors (kill-test 'stop-process)) ; => nil
(kill-test 'quit-process)		  ; => "quit: 3\n"
(kill-test 'interrupt-process)		; => "interrupt: 2\n"

(defun shell-command-with-sentinel (command)
  (interactive "sShell command: ")
  (lexical-let ((buf "*Shell Command Output*"))
    (set-process-sentinel
     (start-process-shell-command "shell" buf command)
     (lambda (proc stat)		;先頭を表示する
       (pop-to-buffer buf)
       (goto-char (point-min))))))

P283

Emacs Lispテクニックバイブル

Emacs Lispテクニックバイブル