views:

32

answers:

1

Hi there

I'm writing a java application where I require to run a process in background throughout the lifetime of the running application.

Here's what I have:

Runtime.getRuntime().exec("..(this works ok)..");
Process p = Runtime.getRuntime().exec("..(this works ok)..");
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);

So, basically I print out every br.readLine().

The thing that I'm not sure about is how to implement this code in my application because wherever I put it (with Runnable), it blocks other code from running (as expected).

I've used Runnable, Thread, SwingUtilities, and nothing works...

Any help would be greatly appreciated :)

+1  A: 

You can read the input stream(i.e br.readLine()) in a thread. That way, it's always running in the background.

The way we have implemented this in our application is roughly like below:

Business logic, i.e the place where you invoke the script:

// Did something...

InvokeScript.execute("sh blah.sh"); // Invoke the background process here. The arguments are taken in processed and executed.

// Continue doing what you were doing

InvokeScript.execute() will look something like below:

InvokeScript.execute(String args) {
// Process args, convert them to command array or whatever is comfortable

Process p = Runtime.getRuntime().exec(cmdArray);

ReaderThread rt = new ReaderThread(p.getInputStream());
rt.start();
}

ReaderThread should continue reading the output of the process you have started, as long as it lasts.

Please note that the above is only a pseudo code.

pavanlimo
Thanks pavanlimo, any advice on when and where to start the Process = Runtime.getRuntime().exec(?
phillyville
Please see my edit above.
pavanlimo
Thanks a bunch pavanlimo, I've tested the code on the browser and it works like a charm, but I'm actually looking for something for Java desktop application. Do you know the equivalent of InvokeScript and ReaderThread in java?
phillyville
Nvm, ReaderThread works :) thanks again!!
phillyville
@phillyville, in case it's not clear yet, ReaderThread and InvokeScript should be your own Java classes. :)
pavanlimo
Yup, I figured that :) I created a new Thread class to do the work.. Thanks again!
phillyville