gpt4 book ai didi

Java运行时进程waitfor并没有出现等待

转载 作者:行者123 更新时间:2023-12-02 07:57:55 25 4
gpt4 key购买 nike

我必须编写一个程序,该程序需要通过命令行调用来运行多个其他程序。程序 1 生成一个文件,然后程序 2 读取该文件。我已经遵循了有关如何安全地执行此操作的各种示例,但仍然遇到一个恼人的问题。下面的代码基本上可以工作,但前提是 waitfor() 之后的 system.out 存在。如果我把它拿出来,我会得到错误(见下文)。如果我不知道为什么会发生某些事情,我会对代码感到有些不舒服。

感谢任何帮助。

代码:

public static int executeCommandWithOutputfile(String command,
String outputFile) {
int exitVal = 0;

try {
FileOutputStream fos = new FileOutputStream(outputFile);
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(command);

// 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???
exitVal = proc.waitFor();
//don't remove this system out, when I did I got errors.
//System.out.println("ExitValue: " + exitVal);
fos.flush();
fos.close();
} catch (Throwable t) {
t.printStackTrace();
}
return exitVal;
}

System.out 行完好无损的输出:

    ExitValue: 0
ExitValue: 0
ExitValue: 0
Release note complete.

删除 system.out 后的输出:

    [Fatal Error] tmpRelNote2482381115742032425xml:1:1: Premature end of file.
Error : The XML config file is not valid!
Exception in thread "main" java.lang.NullPointerException
at rwe.release.CreateReleaseNote.insertReleaseInfo(CreateReleaseNote.java:96)
at rwe.release.CreateReleaseNote.writeReleaseNote(CreateReleaseNote.java:81)
at rwe.release.CreateReleaseNote.<init>(CreateReleaseNote.java:30)
at rwe.release.CreateReleaseNote.main(CreateReleaseNote.java:19)
Process exited with exit code 1.

最佳答案

您的代码存在竞争条件。当您调用 fos.close() 时,OutputGobbler 可能会也可能不会完成吞噬进程的输出。 println 减慢了该线程的速度,足以让 gobbler 有时间完成进程输出的处理。

在关闭文件之前,您必须确保OutputGobbler已完成将所有输出传输到文件。

关于Java运行时进程waitfor并没有出现等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9381473/

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