help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Fun with async processes


From: tomas
Subject: Re: Fun with async processes
Date: Tue, 1 Feb 2022 11:50:14 +0100

On Tue, Feb 01, 2022 at 09:54:24AM +0100, Manuel Giraud wrote:
> <tomas@tuxteam.de> writes:
> 
> > An obvious approach is to have each sentinel call a "global" sentinel
> > which checks whether there are any processes still running (akin to your
> > myrun, only that it just gets called after each process's
> > termination).
> 
> So I have to have an external variable that lists all the processes?

You have it already...

> (defun myrun ()
>  (interactive)
>   (let ((processes (list (chatty) (thinker))))

... here

> > Alternatively (this is typically the approach I take) is to have one
> > sentinel [...]

> Do you have an example or somewhere to look at in emacs for this
> approach? Thanks.

I haven't one handy, sorry. But to illustrate my proposal (caveat:
untested!), I'll munge your code in that direction (sorry for that):

(defun my-sentinel (tag process event)
  (when (string-match "finished" event)
    (cond
      ((eq tag 'chatty)
       (message "Chatty has finished talking."))
      ((eq tag 'thinker)
       (message "Thinker has finished thinking."))
      (t
       (message "Process %S has finished. I don't know that guy" tag)))
    (kill-buffer (process-buffer process))))

(defun chatty ()
  (let* ((buffer (generate-new-buffer "chatty"))
         (process (start-process-shell-command
                   (buffer-name buffer) buffer
                   "find ~/.emacs.d -type f")))
    (when process
      (set-process-sentinel process
        (lambda (process event) (my-sentinel 'chatty process event))
        process))))

(defun thinker ()
  (let* ((buffer (generate-new-buffer "thinker"))
         (process (start-process-shell-command
                   (buffer-name buffer) buffer
                   "for i in $(jot 10); do (echo $i && sleep $i) done")))
    (when process
      (set-process-sentinel process
        (lambda (process event) (my-sentinel 'thinker process event))
        process))))

Embellishments always possible, of course. For example, instead of
putting everywhere a (lambda (...) ...), you could build a function
`make-sentinel' taking a tag and returning a sentinel; Also, instead of
that `cond' which gets longer and longer, you could have a hash table
dispatching to the tag-specific code; Your `make-sentinel' could
populate that hash table.

If you (or your application) prefer static code to this (admittedly
highly) dynamic approach, you might consider translating all that to
the macro realm.

Lots of fun :)

Cheers
-- 
t

Attachment: signature.asc
Description: PGP signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]