开发者

Get Java Runtime Process running in background

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)..");
I开发者_运维知识库nputStream 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 :)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜