Process process = Runtime.getRuntime().exec("tasklist"); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); process.waitFor();
waitFor. public abstract int waitFor() throws InterruptedException. Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.
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.
public ProcessBuilder(String... command) Constructs a process builder with the specified operating system program and arguments. This is a convenience constructor that sets the process builder's command to a string list containing the same strings as the command array, in the same order.
There are many reasons that waitFor()
doesn't return.
But it usually boils down to the fact that the executed command doesn't quit.
This, again, can have many reasons.
One common reason is that the process produces some output and you don't read from the appropriate streams. This means that the process is blocked as soon as the buffer is full and waits for your process to continue reading. Your process in turn waits for the other process to finish (which it won't because it waits for your process, ...). This is a classical deadlock situation.
You need to continually read from the processes input stream to ensure that it doesn't block.
There's a nice article that explains all the pitfalls of Runtime.exec()
and shows ways around them called "When Runtime.exec() won't" (yes, the article is from 2000, but the content still applies!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With