当我应用命令命令时,我没有得到任何输出。如何在使用命令时获得输出或两种情况下都不获得输出?
public class test
{
public static void main(String args[])
{
System.out.println(
systemtest("ifconfig | awk 'BEGIN { FS = \"\n\"; RS = \"\" } { print $1 $2 }' | sed -e 's/ .*inet addr:/,/' -e 's/ .*//'"));
}
public static String systemtest(String cmds)
{
String value = "";
try
{
String cmd[] = {
"/bin/sh",
"-c",
cmds
};
Process p=Runtime.getRuntime().exec(cmd);
// Try 0: here? wrong
//p.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
// Try 1: here?
//p.waitFor();
while(line!=null)
{
value += line + "\n";
line=reader.readLine();
}
// Try 2: here?
p.waitFor();
} catch(IOException e1) {
} catch(InterruptedException e2) {
}
return value;
}
最佳答案
在调用 p.waitFor()
之前,您需要读取命令的输出。
事实:
- 外部命令的输出通过操作系统级“管道”传送。
- 管道的缓冲量有限。
- 如果某个生产者进程尝试写入“已满”的管道,该进程将被迫等待,直到消费者进程从管道中读取了一些数据。
(从上述事实中)不难看出,如果外部应用程序产生的输出多于管道缓冲区(在操作系统空间中)所能容纳的输出,那么应用程序的编写方式将导致死锁。
(即使这不是这次问题的真正原因,其他时候也可能是这样。在读取/写入外部进程时请注意死锁。)
关于java - 如何让管道命令也返回 Java exec 中的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8034939/