我有这句话来执行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
无法执行完毕。
我不知道为什么我被投了票。很抱歉,这是一个不恰当的问题。我编辑了。
答案 0 :(得分:4)
你试过吗?
Process process = new ProcessBuilder("foo.exe","param1","param2").start();
process.waitFor();
答案 1 :(得分:4)
添加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;
}
答案 2 :(得分:1)
如果您不想等待它终止,您可以通过调用exitValue()来检查它是否已终止,而不会阻止您当前的线程执行:
initWithCoder: