【发布时间】:2016-04-30 18:12:57
【问题描述】:
我正在使用 ProcessBuilder 启动一个外部进程,但我需要能够杀死它。现在我杀死进程没有问题,但由于某种原因错误流没有关闭,所以读取流的线程永远不会完成。这使我无法关闭我的程序。
这里是我开始从输入和错误流中读取线程的地方。
final Thread inputPrinter = new Thread() {
public void run() {
BufferedReader inputStream = new BufferedReader(new InputStreamReader(builder.getInputStream()));
String line;
try {
while ((line = inputStream.readLine()) != null) {
Util.println(line, false);
}
} catch (IOException e) {
} finally {
Util.println("input end");
try {
inputStream.close();
} catch (IOException e) {
}
}
}
};
inputPrinter.start();
Thread errorPrinter = new Thread() {
public void run() {
BufferedReader errorStream = new BufferedReader(new InputStreamReader(builder.getErrorStream()));
String line;
try {
while ((line = errorStream.readLine()) != null) {
Util.println(line, true);
}
} catch (IOException e) {
} finally {
Util.println("error end");
try {
errorStream.close();
} catch (IOException e) {
}
}
}
};
errorPrinter.start();
builder.waitFor();
Util.println("");
Util.println("Finished building project.");
这是我停止进程的代码。
try {
builder.getOutputStream().close();
builder.getInputStream().close();
builder.getErrorStream().close();
} catch (IOException e) {
e.printStackTrace();
}
builder.destroy();
Util.println("");
Util.println("Build aborted by user.", true);
当我尝试停止该过程时,我会打印以下内容。
构建被用户中止。
已完成的建筑项目。
输入端
我从来没有得到“错误结束”,调试程序显示线程只是坐在“readLine()”。
等待进程的代码在它自己的线程中运行(与杀死进程的代码分开)。
我需要做什么来确保 errorPrinter 线程终止?
【问题讨论】:
-
如果在调用destroy之前不关闭流会怎样?
-
所有空的 catch 块是怎么回事?你知道这不仅仅是糟糕的代码,它是彻头彻尾的危险代码。
-
如果我之前没有在流上调用 close,会发生完全相同的事情。如果我不在乎它是否停止,为什么空的 catch 块很危险?
标签: java processbuilder