输出停止从我的进程中读取
我有一些非常简单的 Java 代码,在其中启动另一个进程并尝试将所有标准输出和标准错误记录到 SLF4J。
this.service.serverProcess = Runtime.getRuntime().exec(arguments);
this.service.serverIsRunning = true;
BufferedReader serverStdout = new BufferedReader(new InputStreamReader(
this.service.serverProcess.getInputStream()), 16);
BufferedReader serverStderr = new BufferedReader(new InputStreamReader(
this.service.serverProcess.getErrorStream()), 16);
String stdoutLine = null;
String stderrLine = null;
while ((stdoutLine = serverStdout.readLine()) != null ||
((stderrLine = serverStderr.readLine()) != null)) {
if (stdoutLine != null && stdoutLine.trim().length() > 0)
logger.info("{}", stdoutLine);
if (stderrLine != null && stderrLine.trim().length() > 0)
logger.error("{}", stderrLine);
}
try { this.service.serverProcess.waitFor(); } catch (InterruptedException e) {};
this.service.serverIsRunning = false;
不幸的是,我只从进程中获得第一行输出,我从未看到比这更多的输出,尽管我确信输出比我看到的要多得多。
这里出了什么问题?我希望它在事件发生后立即记录,因为输出对于我保留的日志很重要。如何获得进程的 STDOUT 和 STDERR 的完整输出?
I have some pretty simple Java code in which I'm starting another process and attempting to log all standard out and standard error to SLF4J.
this.service.serverProcess = Runtime.getRuntime().exec(arguments);
this.service.serverIsRunning = true;
BufferedReader serverStdout = new BufferedReader(new InputStreamReader(
this.service.serverProcess.getInputStream()), 16);
BufferedReader serverStderr = new BufferedReader(new InputStreamReader(
this.service.serverProcess.getErrorStream()), 16);
String stdoutLine = null;
String stderrLine = null;
while ((stdoutLine = serverStdout.readLine()) != null ||
((stderrLine = serverStderr.readLine()) != null)) {
if (stdoutLine != null && stdoutLine.trim().length() > 0)
logger.info("{}", stdoutLine);
if (stderrLine != null && stderrLine.trim().length() > 0)
logger.error("{}", stderrLine);
}
try { this.service.serverProcess.waitFor(); } catch (InterruptedException e) {};
this.service.serverIsRunning = false;
Unfortunately, I'm only getting the very first line of output from my process, I never see any more output than that, though I'm sure that there is much more output than what I'm seeing.
What's going wrong here? I'd like it to log just about as soon as the event happens, as the output is important to the logs I'm keeping. How can I get the full output of STDOUT and STDERR of my Process?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我怀疑问题是你从来没有从 stderr 读取 - 所以如果进程已经填满了 stderr 的任何缓冲区但没有将任何内容打印到 stdout,那么你将阻止尝试读取 stdout。
我建议您在不同的线程中启动一个读取循环:一个从 stdout 读取,一个从 stderr 读取。
I suspect the problem is that you're never reading from stderr - so if the process has filled up whatever buffer it has for stderr but hasn't printed anything to stdout, you'll be blocking trying to read stdout.
I suggest you start one of the reading loops in a different thread: one reads from stdout and one reads from stderr.