(define (call-with-output-processor-sock command proc)
  "Call COMMAND, a list of strings representing an executable with its
arguments, and apply PROC to every line printed to standard output or
standard error.  Return the exit status of COMMAND."
  ;; We can only capture a program's standard error by parameterizing
  ;; current-error-port to a *file* port before using open-pipe*.  The
  ;; process will write its standard error stream to the provided file
  ;; descriptor.  Meanwhile we read from the file descriptor
  ;; (blocking) for new lines until the process exits.
  (match (socketpair PF_UNIX SOCK_STREAM 0)
    ((in . out)
     (let ((err (dup out)))
       (catch #true
         (lambda ()
           (let ((thread
                  (parameterize ((current-error-port err)
                                 (current-output-port out))
                    (call-with-new-thread
                     (lambda ()
                       (let ((return
                              (status:exit-val
                               (apply system* command))))
                         (close-port err)
                         (close-port out)
                         return))))))
             (let loop ()
               (match (read-line in 'concat)
                 ((? eof-object?)
                  (join-thread thread))
                 (line
                  (proc line)
                  (loop))))))
         (lambda (key . args)
           (for-each
            (lambda (port)
              (false-if-exception (close-port port)))
            (list err out in))
           (apply throw key args)))))))

Generated by Ricardo Wurmus using scpaste at Tue Jul 5 12:38:19 2022. CEST. (original)