Java process.waitFor() 不返回 [英] Java process.waitFor() does not return
问题描述
在 64 位 Windows 7 上,运行 64 位 Java 1.7.0_17 ,下面显示的 p.waitFor()
永远不会返回.
String move_command="cmd.exe/c xcopy/Y/E "+x86_release+" "+path+"\\";过程 p;p = Runtime.getRuntime().exec(move_command);p.waitFor();
如果我使用 Windows 资源管理器,看起来所有文件都被复制(相同数量、相同大小等)
如果我执行以下操作,它 waitFor()
确实会返回:
String move_command="cmd.exe/c move/Y "+x86_release+" "+path+"\\";过程 p;p = Runtime.getRuntime().exec(move_command);p.waitFor();
xcopy
和 move
之间有什么不同,可以防止 waitFor()
返回,或者我走错了路完全?
xcopy
可能恰好比 move
产生更多的输出,填满输出缓冲区并阻塞直到它被冲洗掉.Java 中的默认行为是将子进程的 stdout/stderr 通过管道传输到 InputStream
中,然后您需要以编程方式读取这些内容,以免子进程的缓冲区溢出.
如果是后者,解决方案很简单,事实上你应该这样做:使用ProcessBuilder
准备系统调用并在其上调用inheritIO
.这将为子进程重用父进程的标准输入和标准输出.
附注,xcopy
是一个常规的 .exe
文件,不需要包装到 cmd.exe/c
中.>
On Windows 7 64 bit, running 64 bit Java 1.7.0_17 , the p.waitFor()
shown below never returns.
String move_command="cmd.exe /c xcopy /Y /E "+x86_release+" "+path+"\\";
Process p;
p = Runtime.getRuntime().exec(move_command);
p.waitFor();
If I use Windows Explorer, it looks like all the files are copied (same number, same size, etc.)
If I do the below, it waitFor()
does return:
String move_command="cmd.exe /c move /Y "+x86_release+" "+path+"\\";
Process p;
p = Runtime.getRuntime().exec(move_command);
p.waitFor();
What could be so different between an xcopy
and a move
that keeps waitFor()
from returning, or am I on the wrong track entirely?
xcopy
probably just happens to produce more output than move
, filling up the out-buffer and blocking until it is flushed. The default behavior in Java is to pipe the subprocess's stdout/stderr into InputStream
s that you are then required to read programmatically lest the subprocess's buffers overflow.
If the latter is the case, the solution is simple, and in fact you should do that anyway: use ProcessBuilder
to prepare the system call and call inheritIO
on it. This will reuse your parent process`s stdin and stdout for the subprocess.
A side note, xcopy
is a regular .exe
file and doesn't need wrapping into cmd.exe /c
.
这篇关于Java process.waitFor() 不返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!