[Top][All Lists]

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

Filter IO through an external command

From: Tristan Colgate
Subject: Filter IO through an external command
Date: Thu, 23 Feb 2012 14:26:28 +0000


  I just got this working and thought people mind find it useful. It
passes IO through an external command (I'm using it to get svg output
from dot to include inline in html). I tried using
open-input-output-pipe but hit issues.

  It could probably handle errors nicely. Comments very welcome:

(use-modules (ice-9 rdelim))

(define (filter inproc outproc cmd . args)
  "filter the output of inproc via cmd to outproc through an external cmd"
  (let* ((read-pipe (pipe))
         (read-in  (car read-pipe))
         (read-out  (cdr read-pipe))
         (write-pipe (pipe))
         (write-in  (car write-pipe))
         (write-out  (cdr write-pipe))
         (child-pid    (primitive-fork)))
    (if (= child-pid 0)
          (close-output-port read-out)
          (close-input-port write-in)
          (dup2 (fileno read-in) 0)
          (dup2 (fileno write-out) 1)
          (apply execlp (append (list cmd) (append (list cmd) args))))
          (close-input-port read-in)
          (close-output-port write-out)
          (parameterize ((current-output-port read-out))
          (close-output-port read-out)
          (parameterize ((current-input-port write-in))
          (close-input-port write-in)
          (waitpid child-pid 0)))))

; To use
> (filter
      (display "Hello World!")(newline))
      (let loop ((line (read-line)))
        (if (not  (eof-object? line))
            (write-line line)
            (loop (read-line))))))
    "sed" "s/World/Planet/")
Hello Planet!
$4 = (3892 . 0)

Tristan Colgate-McFarlane
  "You can get all your daily vitamins from 52 pints of guiness, and a
glass of milk"

reply via email to

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