Java的执行exec()不返回预期的管道'连接的命令结果 [英] Java exec() does not return expected result of pipes' connected commands
问题描述
我打电话是由管道连接的命令行程序。所有这一切在Linux是肯定的。
I'm calling command line programs connected by pipes. All this works on Linux for sure.
我的方法:
protected String execCommand(String command) throws IOException {
String line = null;
if (command.length() > 0) {
Process child = Runtime.getRuntime().exec(command);
InputStream lsOut = child.getInputStream();
InputStreamReader r = new InputStreamReader(lsOut);
BufferedReader in = new BufferedReader(r);
String readline = null;
while ((readline = in.readLine()) != null) {
line = line + readline;
}
}
return line;
}
如果我打电话给一些猫文件| grep的ASD 后,我得到预期的结果。但是,并非所有的命令正常工作。比如这个:
If I'm calling some cat file | grep asd, I'm getting the expected result. But not all commands works correctly. For example with this:
cat /proc/cpuinfo | wc -l
或本
cat /proc/cpuinfo | grep "model name" | head -n 1 | awk -F":" '{print substr($2, 2, length($2))}
该方法将返回null。我猜这个问题取决于输出格式化命令一样的头 尾 厕所,等我如何解决此问题,并得到输出的最终结果?
the method will return null. I'm guessing this problem depends on output formatting commands like head, tail, wc, etc. How I can work around this problem and get the final result of the output?
推荐答案
还是没有找到妥善的解决办法与执行的Runtime.exec管道命令,但发现了一个解决方法。我只是写了这些脚本分离的bash文件。随后的Runtime.exec调用这些的bash脚本,并得到预期的结果。
Still didn't found proper solution to execute piped commands with Runtime.exec, but found a workaround. I've simply wrote these scripts to separate bash files. Then Runtime.exec calls these bash scripts and gets expected result.
这篇关于Java的执行exec()不返回预期的管道'连接的命令结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!