Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Runtime.exec() asynchronous output

I'd like to get the output from a long running shell command as it is available instead of waiting for the command to complete. My code is run in a new thread

Process proc = Runtime.getRuntime().exec("/opt/bin/longRunning");
InputStream in = proc.getInputStream();
int c;
while((c = in.read()) != -1) {
    MyStaticClass.stringBuilder.append(c);
}

The problem with this is that my program in /opt/bin/longRunning has to complete before the InputStream gets assigned and read. Is there any good way to do this asynchronously? My goal is that an ajax request will return the current value MyStaticClass.stringBuilder.toString() every second or so.

I'm stuck on Java 5, fyi.

Thanks! W

like image 741
wmarbut Avatar asked Oct 13 '11 17:10

wmarbut


People also ask

How does Java Runtime exec work?

exec(String command) method executes the specified string command in a separate process. This is a convenience method. An invocation of the form exec(command) behaves in exactly the same way as the invocation exec(command, null, null).

How does runtime getRuntime exec work?

getRuntime(). exec() method to use the command-line to run an instance of the program "tesseract". the first argument calls the tesseract program, the second is the absolute path to the image file and the last argument is the path and name of what the output file should be.

Does Java support asynchronous programming?

Since Java 5, the Future interface provides a way to perform asynchronous operations using the FutureTask. We can use the submit method of the ExecutorService to perform the task asynchronously and return the instance of the FutureTask.


2 Answers

Try with Apache Common Exec. It has the ability to asynchronously execute a process and then "pump" the output to a thread. Check the Javadoc for more info

like image 171
LordDoskias Avatar answered Sep 21 '22 12:09

LordDoskias


Runtime.getRuntime().exec does not wait for the command to terminate, so you should be getting the output straight away. Maybe the output is being buffered because the command knows it is writing to a pipe rather than a terminal?

like image 39
Paul Cager Avatar answered Sep 19 '22 12:09

Paul Cager