英文:
When/why does Java Runtime.exec() require cmd.exe?
问题
在我的Java代码中,我发现两个类似的命令之间存在相当大的性能差异:
execString = new String[]{"CMD.EXE", "/C", path_to_executable};
Runtime.getRuntime().exec(command)
比起以下命令:
execString = new String[]{path_to_executable};
Runtime.getRuntime().exec(command)
第一个命令运行我的可执行文件几乎快了两倍(6-7分钟对比 3-4分钟),而第二个命令是告诉可执行文件直接运行,而另一个是告诉 cmd.exe 运行可执行文件...?
谢谢提前回答
*编辑:
使用 ProcessBuilder 时也注意到了相同的性能差异:
ProcessBuilder myPB = new ProcessBuilder(execString);
Process myProcess = myPB.start();
英文:
In my Java code I have found quite significant performance differences between two similar commands:
execString=new String[]{"CMD.EXE","/C", path_to_executable };
Runtime.getRuntime().exec(command)
runs my executable almost twice as quickly (6-7mins vs 3-4mins) as:
execString=new String[]{" path_to_executable };
Runtime.getRuntime().exec(command)
Please can someone educate me as to why? One seems to be telling the executable to run directly, whereas the other is telling cmd.exe to run the executable...?
Thanks in advance
EDIT:
The same performance discrepancies were noted when using ProcessBuilder:
ProcessBuilder myPB = new ProcessBuilder(execString);
Process myProcess = myPB.start();
答案1
得分: 2
我在这里找到了答案:
https://stackoverflow.com/a/24676491/1961025
从java.lang.Process的API文档中可以看到:
由于一些本地平台仅为标准输入和输出流提供有限的缓冲区大小,如果未及时写入子进程的输入流或读取输出流,可能会导致子进程阻塞,甚至死锁。
基本上,您需要确保进程处理输入、输出和错误流。 我的情况不是这样。 当使用cmd.exe时,我认为它会包装可执行文件,所以这不是问题。 使用来自https://www.infoworld.com/article/2071275/when-runtime-exec---won't.html?page=2的gobblers效果很好!
谢谢!
英文:
I have discovered the answer here:
https://stackoverflow.com/a/24676491/1961025
> From the API doc of java.lang.Process:
>
> > Because some native platforms only provide limited buffer size for
> > standard input and output streams, failure to promptly write the input
> > stream or read the output stream of the subprocess may cause the
> > subprocess to block, or even deadlock.
Basically, you need to make sure that the process is handling the input, output and error streams. Mine wasn't. When using cmd.exe, I think it kind of wraps the executable so it's not an issue. Using the gobblers from https://www.infoworld.com/article/2071275/when-runtime-exec---won-t.html?page=2 works a treat!
Thanks!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论