gpt4 book ai didi

java - Spring Boot 从 Runtime.getRuntime().exec() 开始,一直等待,直到调用者进程终止

转载 作者:行者123 更新时间:2023-12-02 02:50:01 26 4
gpt4 key购买 nike

我有两个 Spring Boot 应用程序,一个称为 ProcessCenter,它是一些移动和桌面应用程序的 API,另一个称为 Watcher,负责保持一切运行。

我的问题:

当Watcher看到ProcessCenter关闭时,他调用Runtime.getRuntime().exec( "java -jar ProcessCenter.jar"),然后ProcessCenter开始启动,但卡住了,我没有错误,没有日志,什么也没有,只是保持卡住,直到观察者关闭,然后它恢复启动并正常工作

帮助任何人吗?

最佳答案

根据JDK的Javadoc文档:“一些原生平台只为标准输入输出流提供有限的缓冲区大小,未能及时写入子进程的输入流或读取子进程的输出流可能会导致子进程阻塞,甚至陷入僵局。”

您可以按照这篇文章来帮助您正确实现外部进程调用,帮助您管理缓冲区 -> https://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html?page=2

总而言之,您可以创建一个可以管理缓冲区限制的类,处理程序的输出,无论它有多大。一个例子:

import java.util.*;
import java.io.*;
class StreamGobbler extends Thread
{
InputStream is;
String type;
OutputStream os;

StreamGobbler(InputStream is, String type)
{
this(is, type, null);
}
StreamGobbler(InputStream is, String type, OutputStream redirect)
{
this.is = is;
this.type = type;
this.os = redirect;
}

public void run()
{
try
{
PrintWriter pw = null;
if (os != null)
pw = new PrintWriter(os);

InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null)
{
if (pw != null)
pw.println(line);
System.out.println(type + ">" + line);
}
if (pw != null)
pw.flush();
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
public class GoodWinRedirect
{
public static void main(String args[])
{
if (args.length < 1)
{
System.out.println("USAGE java GoodWinRedirect <outputfile>");
System.exit(1);
}

try
{
FileOutputStream fos = new FileOutputStream(args[0]);
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("java jecho 'Hello World'");
// any error message?
StreamGobbler errorGobbler = new
StreamGobbler(proc.getErrorStream(), "ERROR");

// any output?
StreamGobbler outputGobbler = new
StreamGobbler(proc.getInputStream(), "OUTPUT", fos);

// kick them off
errorGobbler.start();
outputGobbler.start();

// any error???
int exitVal = proc.waitFor();
System.out.println("ExitValue: " + exitVal);
fos.flush();
fos.close();
} catch (Throwable t)
{
t.printStackTrace();
}
}
}

关于java - Spring Boot 从 Runtime.getRuntime().exec() 开始,一直等待,直到调用者进程终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44004368/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com