简体   繁体   English

ProcessBuilder和Process.waitFor(),等了多久?

[英]ProcessBuilder and Process.waitFor(), how long does it wait?

I am executing an .exe-file from java, using the ProcessBuilder class and the Process class.我正在使用ProcessBuilder类和Process类从 java 执行 .exe 文件。 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?我只是想知道,“waitFor()”要等多久? Is it waiting until my .exe is executed, or is it waiting till its execution is finished?是等待我的 .exe 执行,还是等待执行完成?

My .exe is a compiled AutoIt-script.我的 .exe 是一个编译的 AutoIt 脚本。 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 之后我的 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.我想要实现的是两个脚本的轮换执行,但恐怕我的 Java 代码正在执行第二个脚本,而第一个脚本仍在运行。 Has anyone a workaround for this?有没有人解决这个问题? I am glad for any ideas.我很高兴有任何想法。

Your current execution thread will be blocked on process.waitFor() until process is terminated (ie execution finished).您当前的执行线程将在process.waitFor()上被阻塞,直到进程终止(即执行完成)。 Source here来源在这里

Also note that if process is already terminated : waitFor() will not be blocked.另请注意,如果进程已经终止:waitFor() 将不会被阻塞。 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 (ie not just calling start multiple times on the same Process: it won't work after first execution)我不知道你在你的问题中输入的代码是否正是你运行的......但是你必须小心并为你的脚本的每次执行重新创建一个新的 Process 实例(即不仅仅是多次调用 start相同的过程:第一次执行后它不会工作)

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()将被挂起。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM