ProcessBuilder and Process.waitFor(), how long does ist wait?

白昼怎懂夜的黑 提交于 2019-11-30 08:59:30

问题


I am executing an .exe-file from java, using the ProcessBuilder class and the Process class. To explain what I am doing:

 builder = new ProcessBuilder(commands);
 builder.redirectErrorStream(true);
 Process process = builder.start();
 process.waitFor();

I just wanted to know, for how long is "waitFor()" waiting? Is it waiting until my .exe is executed, or is it waiting till its execution is finished?

My .exe is a compiled AutoIt-script. That means, that there could be interactions like mouse movements, which take some time. So I need to know if my Java-code execution goes on after calling the .exe or if it is really waiting for it.

What I want to achieve is the rotational execution of two scripts, but I'm afraid, that my Java code is executing the second script while the first one is still running. Has anyone a workaround for this? I am glad for any ideas.


回答1:


Your current execution thread will be blocked on process.waitFor() until process is terminated (i.e. execution finished). Source here

Also note that if process is already terminated : waitFor() will not be blocked. I don't know if the code you put in your question is exactly what you run... but you must be careful and re-create a new instance of Process for every execution of your script (i.e. not just calling start multiple times on the same Process: it won't work after first execution)




回答2:


Additionally, If there are outputs in the "commands". you should read the standard output and standard error output by stream(process.getErrorStream()) and process.getInputStream()).If not and output or error output be full, the waitfor() would be hanged.




回答3:


It will wait till process is finished. Workaround:

1 Use isAlive()

2 Use waitFor(long timeout, TimeUnit unit) (Only 1.8)



来源:https://stackoverflow.com/questions/29746304/processbuilder-and-process-waitfor-how-long-does-ist-wait

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!