Java ProcessBuilder和Process.waitFor(),等了多久?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29746304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ProcessBuilder and Process.waitFor(), how long does it wait?
提问by KJaeg
I am executing an .exe-file from java, using the ProcessBuilderclass and the Processclass. To explain what I am doing:
我正在使用ProcessBuilder类和Process类从 java 执行 .exe 文件。解释我在做什么:
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?
我只是想知道,“waitFor()”要等多久?是等待我的 .exe 执行,还是等待执行完成?
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.
我的 .exe 是一个编译的 AutoIt 脚本。这意味着,可能会有鼠标移动之类的交互,这需要一些时间。所以我需要知道在调用 .exe 之后我的 Java 代码执行是否继续,或者它是否真的在等待它。
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.
我想要实现的是两个脚本的轮换执行,但恐怕我的 Java 代码正在执行第二个脚本,而第一个脚本仍在运行。有没有人解决这个问题?我很高兴有任何想法。
采纳答案by ben75
Your current execution thread will be blocked on process.waitFor()
until process is terminated (i.e. execution finished).
Source here
您当前的执行线程将被阻塞,process.waitFor()
直到进程终止(即执行完成)。来源在这里
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)
另请注意,如果进程已经终止:waitFor() 将不会被阻塞。我不知道你在你的问题中输入的代码是否正是你运行的......但是你必须小心并为你的脚本的每次执行重新创建一个新的 Process 实例(即不仅仅是多次调用 start相同的过程:第一次执行后它不会工作)
回答by Evgeniy Dorofeev
It will wait till process is finished. Workaround:
它将等到过程完成。解决方法:
1 Use isAlive()
1 使用 isAlive()
2 Use waitFor(long timeout, TimeUnit unit) (Only 1.8)
2 使用waitFor(long timeout, TimeUnit unit) (仅1.8)
回答by Dorleeze
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.
此外,如果“命令”中有输出。你应该通过stream(process.getErrorStream())
和读取标准输出和标准错误输出process.getInputStream())
。如果不是并且输出或错误输出已满,waitfor()
则将被挂起。