获取在后台运行的 Java 运行时进程

发布于 2024-09-19 17:27:00 字数 529 浏览 8 评论 0原文

我正在编写一个java应用程序,我需要在正在运行的应用程序的整个生命周期中在后台运行一个进程。

这就是我所拥有的:

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

所以,基本上我打印出了每个 br.readLine() 。

我不确定的是如何在我的应用程序中实现此代码,因为无论我将其放在何处(使用 Runnable),它都会阻止其他代码运行(如预期)。

我使用过 Runnable、Thread、SwingUtilities,但没有任何效果...

任何帮助将不胜感激:)

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

九歌凝 2024-09-26 17:27:00

您可以在线程中读取输入流(即br.readLine())。这样,它始终在后台运行。

我们在应用程序中实现此功能的方式大致如下所示:

业务逻辑,即调用脚本的位置:

// 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() 将如下所示:

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 应该继续读取您已启动的进程的输出,只要它持续下去。

请注意,上面只是伪代码。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文