On Jan 9, 9:24 pm, Phil Hagelberg <p...@hagelb.org> wrote:
> jaime <xiejianm...@gmail.com> writes:
> > Later on I tried to add code that can make this possible but I found
> > there's no way to detect if a command requires user's input and thus I
> > have to find another way to make it work - but I didn't success and
> > have been struggling for a workaround for a long while....
>
> > anyone has any idea?
>
> As far as I know this is impossible to do without bringing in
> third-party libraries; this is just a (rather serious) shortcoming of
> the JDK. I haven't looked into it enough to know which libraries would
> offer it though.

This should be possible if you don't mind suiciding your own process's
stdin/stdout, by blindly forwarding all your input and output through
the child. But if you send the child some input it didn't need, and it
terminates, and then later you need your own stdin again, some pieces
will be missing.

I was going to attach a simple proof of concept to this, but I can't
seem to get it right. So instead, here's what I was trying to do, and
if someone wants to take it up this might be something useful to work
from:

(ns fork.core
  (:require [clojure.java.io :as io])
  (:import (java.io PipedReader PipedWriter))
  (:gen-class))

(defn -main [& args]
  (println "Start typing, I'll cat it back atcha!")
  (let [child (-> (Runtime/getRuntime) (.exec "/bin/cat"))
        cin (.getInputStream child)
        cout (.getOutputStream child)

        in-pipe-in (PipedReader.)
        in-pipe-out (PipedWriter. in-pipe-in)

        out-pipe-in (PipedReader.)
        out-pipe-out (PipedWriter. out-pipe-in)

        in *in*, out *out*] ;; avoid dynamic-binding issues
    (future (io/copy in in-pipe-out)) ;; read my stdin...
    (future (io/copy in-pipe-in cout)) ;; write it to child's stdin

    (future (io/copy cin out-pipe-out)) ;; read child's stdout...
    @(future (io/copy out-pipe-in out)) ;; write it to my stdout, and
wait for it to finish
    (let [exit-code (.waitFor child)]
      (println "Child process finished with exit code" exit-code)
      exit-code)))

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to