Java Runtime.exec() 何时/为什么需要 cmd.exe?

huangapple go评论53阅读模式
英文:

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 运行可执行文件...?

谢谢提前回答 Java Runtime.exec() 何时/为什么需要 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 Java Runtime.exec() 何时/为什么需要 cmd.exe?

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!

huangapple
  • 本文由 发表于 2020年7月31日 00:57:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63177912.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定