问题描述
我想从Java启动一个进程,读取它的输出,并获取它的返回代码。但是当它正在执行时,我希望能够取消它。我首先启动这个过程:
I want to launch a process from Java, read its output, and get its return code. But while it's executing, I want to be able to cancel it. I start out by launching the process:
ProcessBuilder pb = new ProcessBuilder(args);
pb.redirectErrorStream(true);
Process proc = pb.start();
如果我调用proc.waitFor(),在进程退出之前我无法执行任何操作。所以我假设我需要这样的东西:
If I call proc.waitFor(), I can't do anything until the process exits. So I'm assuming I need to something like this:
while (true) {
see if process has exited
capture some output from the process
decide if I want to cancel it, and if so, cancel it
sleep for a while
}
这是对的吗?有人能给我一个如何用Java做这个的例子吗?
Is this right? Can someone give me an example of how to do this in Java?
推荐答案
这是我想你想做的一个例子:
Here's an example of what I think you want to do:
ProcessBuilder pb = new ProcessBuilder(args);
pb.redirectErrorStream(true);
Process proc = pb.start();
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
int exit = -1;
while ((line = br.readLine()) != null) {
// Outputs your process execution
System.out.println(line);
try {
exit = proc.exitValue();
if (exit == 0) {
// Process finished
}
} catch (IllegalThreadStateException t) {
// The process has not yet finished.
// Should we stop it?
if (processMustStop())
// processMustStop can return true
// after time out, for example.
proc.destroy();
}
}
你可以改进它:-)我不知道有一个真实的环境来测试它,但你可以找到更多的信息。
You can improve it :-) I don't have a real environment to test it now, but you can find some more information here.
这篇关于从Java运行外部程序,读取输出,允许中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!