Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

like image 313
KJaeg Avatar asked Apr 20 '15 11:04

KJaeg


People also ask

What does process waitFor () do?

waitFor. Causes the current thread to wait, if necessary, until the subprocess represented by this Process object has terminated, or the specified waiting time elapses.

How to wait for process to complete in Java?

The waitFor() method of Process class is used to wait the currently executing thread until the process executed by the Process object has been completed. The method returns immediately when the subprocess has been terminated and if the subprocess is not terminated, the thread will be blocked.

What is ProcessBuilder class in Java?

This class is used to create operating system processes. Each ProcessBuilder instance manages a collection of process attributes. The start() method creates a new Process instance with those attributes.


2 Answers

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)

like image 66
ben75 Avatar answered Sep 18 '22 16:09

ben75


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.

like image 23
Dorleeze Avatar answered Sep 20 '22 16:09

Dorleeze