Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

process.waitFor() never returns

Process process = Runtime.getRuntime().exec("tasklist"); BufferedReader reader =      new BufferedReader(new InputStreamReader(process.getInputStream())); process.waitFor(); 
like image 946
user590444 Avatar asked Mar 30 '11 08:03

user590444


People also ask

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

How do you make a Java process wait?

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 in Java?

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.


1 Answers

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!)

like image 85
Joachim Sauer Avatar answered Oct 08 '22 15:10

Joachim Sauer