Get Java Runtime Process running in background

偶尔善良 提交于 2019-12-21 21:47:49

问题


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:


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.



来源:https://stackoverflow.com/questions/3711040/get-java-runtime-process-running-in-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!