gpt4 book ai didi

java - 当从 java 调用 wget 并消耗 "error"和 "output"流时,子进程尝试多次运行不完整的命令

转载 作者:行者123 更新时间:2023-12-01 21:19:14 25 4
gpt4 key购买 nike

我有以下代码:

public void callWget(String WgetCommand) {
System.out.println(WgetCommand);
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(wget_FirstScan);
int exitVal = proc.waitFor();
BufferedReader br= new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String line = null;
while ( (line = br.readLine()) != null)
System.out.println(line);
br.close();
System.out.println("Process exitValue: " + exitVal);
proc.destroy();
} catch ( IOException ioe ) { ioe.printStackTrace(); }
catch ( InterruptedException ie ) { ie.printStackTrace(); }
}

问题是子进程多次尝试运行不完整的 wgetCommand,最后调用完整的命令,一切正常。我相信我还必须处理输入流,因为命令很长。有谁对此有任何想法吗?提前致谢。

最佳答案

The problem is that the subprocess tries to run the incomplete wgetCommand many times and finally it calls the complete command and everything is fine. ... Is there any body who has any idea on this?

我不知道为什么这会导致 wget 命令运行多次。但是,在处理完命令的所有输出之后,我绝对不会调用 proc.waitFor() 。至少在unix下,当进程完成时,底层的输入/输出/错误流将被关闭。此外,如果有大量输出,它可能会填充操作系统缓冲区,直到您读取它,这可能会阻止 wget 完成,从而导致死锁。

所以你应该这样做:

Process proc = rt.exec(wget_FirstScan);
BufferedReader br= new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();

// wait after processing output
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
// no need to call proc.destroy()

此外,您可能希望处理 proc.getInputStream();,它是 wget 命令的“标准输出”。 getErrorStream()wget 打印的错误消息。

关于java - 当从 java 调用 wget 并消耗 "error"和 "output"流时,子进程尝试多次运行不完整的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39418431/

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