Here's a function that creates a thread that waits until a port is closed and then prints a message:
(define (watch-for-port-close p)
(thread (lambda () (sync (port-closed-evt out)) (eprintf "port closed\n"))))
For example:
(define out (open-output-string))
(watch-for-port-close out) ;; => #<thread>
(close-output-port out) ;; prints "port closed"
One reason a port can get closed is because of a custodian shutdown, and in that case you'd need to make sure that the watcher thread and its current-error-port are not managed by the same custodian. Here's a version that creates an unkillable thread (generally a bad idea, but probably okay for debugging):
(require ffi/unsafe/custodian)
(define (watch-for-port-close p)
(parameterize ((current-custodian (make-custodian-at-root)))
(thread (lambda () (sync (port-closed-evt out)) (eprintf "port closed\n")))))
Ryan