我有以下代码;
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()
可以完美运行。p.waitFor()
导致继续阻塞的 io 流的管道是什么?
我很困惑,因为我认为 IO 流是被动的,无法保持进程处于活动状态,或者让 Java 认为进程仍然处于活动状态。