我正在研究ProcessBuilder类,其中说,每个流程生成器管理的一个流程属性如下:
标准输入的来源。默认情况下,子进程从管道读取输入。Java代码可以通过Process.getOutputStream()返回的输出流访问这个管道。但是,标准输入可以使用redirectInput重定向到另一个源。在本例中,Process.getOutputStream()将返回一个空输出流,其中:
然后我查找了名为getOutputStream的API函数,但是它仍然没有点击m。
我不明白这句话是什么意思:
输出到流的管道进入由该流程对象表示的流程的标准输入。
只是寻找澄清或可能的示例代码,这是如何工作的。谢谢
发布于 2016-01-10 01:46:36
这是一个简单的示例代码。
public class ParentProcess {
public static void main(String[] arags) throws IOException, InterruptedException {
Process p = new ProcessBuilder(
"java", "-cp", "bin", "stackoverflow.ChildProcess").start();
// receive from child
new Thread(() -> {
try {
int c;
while ((c = p.getInputStream().read()) != -1)
System.out.write((byte)c);
} catch (Exception e) {
e.printStackTrace();
}
}).start();
// send to child
try (Writer w = new OutputStreamWriter(p.getOutputStream(), "UTF-8")) {
w.write("send to child\n");
}
System.out.println("rc=" + p.waitFor());
}
}
class ChildProcess {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// receive from parent and send to parent
System.out.println("child recevied: " + s.nextLine());
}
}结果是:
child recevied: send to child
rc=0https://stackoverflow.com/questions/34700885
复制相似问题