[英]In java determine if a process created using Runtime environment has finished execution?
[英]determine whether process has done execution in Java
我有这个语句来执行foo.exe
Process process = new ProcessBuilder("foo.exe","param1","param2").start();
我期望的执行顺序是
foo.exe
foo.exe
完成)foo.exe
执行foo.exe
执行完毕我怎样才能做到这一点 ?
编辑:我试过process.waitFor()
,它使foo.exe
永远卡住并且不会终止。 我怀疑foo.exe
无法执行完成。
我真的不明白为什么我被否决了。 抱歉,如果这是一个不恰当的问题。 我编辑了。
你试过吗?
Process process = new ProcessBuilder("foo.exe","param1","param2").start();
process.waitFor();
添加 p.waitFor();
Process p= new ProcessBuilder("foo.exe","param1","param2").start();
p.waitFor(); // this will wait till process finish
已编辑 - 有问题已编辑
一些原生平台只为标准输入输出流提供了有限的缓冲区大小,未能及时写入输入流或读取子进程的输出流可能会导致子进程阻塞,甚至死锁。
试试这个代码:
Process p= new ProcessBuilder("foo.exe","param1","param2").start();
new Thread(new Reader(p.getErrorStream(), System.err)).start();
new Thread(new Reader(p.getInputStream(), System.out)).start();
int returnCode = p.waitFor();
System.out.println("Return code = " + returnCode);
读者班
class Reader implements Runnable
{
public Reader (InputStream istrm, OutputStream ostrm) {
istrm = istrm;
ostrm = ostrm;
}
public void run() {
try
{
final byte[] buffer = new byte[1024];
for (int length = 0; (length = istrm.read(buffer)) != -1; )
{
ostrm.write(buffer, 0, length);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
private final OutputStream ostrm;
private final InputStream istrm;
}
如果您不想等待它的终止,您可以通过调用exitValue()来检查它是否已终止,而不会阻塞您当前的线程执行:
public static boolean hasTerminatedExecution(Process p) {
try {
p.exitValue();
return true;
} catch (IllegalThreadStateException exception) {
return false; // exception thrown if process didn't terminated yet
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.