这是我通过 java 在 Windows 中启动进程的代码(并吞噬输出)。
public static void main(String[] args) throws Exception {
String[] command = new String[3];
command[0] = "cmd";
command[1] = "/C";
command[2] = "test.exe";
final Process child = Runtime.getRuntime().exec(command);
new StreamGobbler(child.getInputStream(), "out").start();
new StreamGobbler(child.getErrorStream(), "err").start();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
child.getOutputStream()));
out.write("exit\r\n");
out.flush();
child.waitFor();
}
private static class StreamGobbler extends Thread {
private final InputStream inputStream;
private final String name;
public StreamGobbler(InputStream inputStream, String name) {
this.inputStream = inputStream;
this.name = name;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
inputStream));
for (String s = in.readLine(); s != null; s = in.readLine()) {
System.out.println(name + ": " + s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
不知何故,有问题的程序(进程)立即收到 EOF(就像在我跨过“exec”行之后一样),因此在调用 runtime.exec 后立即抛出错误(检测到,无效)消息。我可以通过命令提示符手动运行该程序而不会出现此问题,但已确认在 Windows 上发送 ctrl-z 是导致此消息的原因。
有谁知道这可能是什么原因造成的?
如果重要的话,我已经尝试直接将进程作为“test.exe”而不是 cmd /c test.exe 运行,但是当我这样做时,我无法通过 inputStream 看到输出。当我在没有 /c 的情况下执行 cmd test.exe 时,没有区别。