我有以下代码;
String[] cmd = { "bash", "-c", "~/path/to/script.sh" };
Process p = Runtime.getRuntime().exec(cmd);
PipeThread a = new PipeThread(p.getInputStream(), System.out);
PipeThread b = new PipeThread(p.getErrorStream(), System.err);
p.waitFor();
a.die();
b.die();
PipeThread
类非常简单,因此我将完整地包含它;
public class PipeThread implements Runnable {
private BufferedInputStream in;
private BufferedOutputStream out;
public Thread thread;
private boolean die = false;
public PipeThread(InputStream i, OutputStream o) {
in = new BufferedInputStream(i);
out = new BufferedOutputStream(o);
thread = new Thread(this);
thread.start();
}
public void die() { die = true; }
public void run() {
try {
byte[] b = new byte[1024];
while(!die) {
int x = in.read(b, 0, 1024);
if(x > 0) out.write(b, 0, x);
else die();
out.flush();
}
}
catch(Exception e) { e.printStackTrace(); }
try {
in.close();
out.close();
}
catch(Exception e) { }
}
}
我的问题是这样的; p.waitFor()
会无限阻塞,即使在子进程终止之后也是如此。如果我不创建一对PipeThread
实例,那么p.waitFor()
可以正常工作。 io 流的管道是什么导致 p.waitFor()
继续阻塞?
我很困惑,因为我认为 IO 流是被动的,无法使进程保持 Activity 状态,或者使 Java 认为进程仍然 Activity 。
最佳答案
在您的PipeThread
代码中,您将永远循环直到!die - 但您在p.waitFor()
之后调用PipeThread.die()
- 究竟是什么停止了 PipeThread
线程?
关于Java Process.waitFor() 和 IO 流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13359391/