【发布时间】:2014-05-16 13:24:00
【问题描述】:
我想启动一个子进程并读取它的输出,直到 EOF 或内部标志被清除。
我的第一次尝试是在另一个线程中调用InputStream.close(),但是虽然它适用于套接字,但它不适用于Process.getInputStream()的结果:主线程仍在等待read()和杀手线程要么挂在close0()(windows),要么继续没有效果(linux)。
然后我尝试检查InputStream.available(),但它没有检测到EOF:它返回0。
public class BbbTest extends TestCase {
private Process proc;
private InputStream getStream() throws IOException {
//if ("".length() == 0) return new java.net.Socket("intra", 80).getInputStream();
String[] cmd;
if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
cmd = new String[] { "cmd", "/c", "more & more" };
} else {
cmd = new String[] { "sh", "-c", "cat; cat" };
}
Process proc = Runtime.getRuntime().exec(cmd);
return proc.getInputStream();
}
public void testB() throws Exception {
final InputStream in = getStream();
final Thread readingThread = Thread.currentThread();
Thread t = new Thread("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") {
@Override
public void run() {
try {
sleep(1000);
if (proc != null) proc.destroy(); // this won't help
readingThread.interrupt(); // this won't help either
in.close(); // this will do nothing and may even hang
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException ( );
}
}
};
t.setDaemon(true);
t.start();
try {
in.read();
assertTrue(false);
} catch (IOException e) {
// nothing
}
}
}
我最后的希望是从返回的流中窃取频道并使用 nio
【问题讨论】:
-
您想读取其他进程写入流中的内容还是要杀死该进程
-
@Mani srsly,“我想启动一个子进程并读取它的输出”
-
那么为什么要试图杀死/关闭流。并且您正在执行的命令不会自行终止(更多和更多)
-
@Mani 这只是一个例子。我不介意它是否被杀死,但主要目标是退出 read()
-
请看我的回答。如果您想阅读,可以使用它来阅读。