如何让管道命令也返回 Java exec 中的输出?
当我应用命令命令时,我没有得到任何输出。如何在使用命令或两种情况下都不获得输出?
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;
}
When i apply command command i do not get any output. How can i get output while using command or not both case?
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要在调用
p.waitFor()
之前读取命令的输出。事实:
不难看出(从上述事实),如果外部应用程序产生的输出多于管道缓冲区(在操作系统空间中)所能容纳的输出,那么应用程序的编写方式将导致死锁。
(即使这不是这次问题的真正原因,其他时候也可能是这样。在读取/写入外部进程时请注意死锁。)
You need to read the output from the command before you call
p.waitFor()
.Facts:
It is not hard to see (from the above facts) that the way that you're application is written will result in a deadlock if the external application produces more output than can fit into the pipe's buffer (in O/S space).
(Even if this is not the real cause of your problem this time, it could be other times. Watch out for deadlocks when reading from / writing to external processes.)
您需要了解如何处理 stdout、stderr 和流管道。
或者,您可能有兴趣查看 Commons Exec 和 Commons CLI
我希望它能帮助你。
祝你好运!
You need to understand how to handle stdout, stderr and stream piping.
Alternatively, you might be interested to take a look on Commons Exec and Commons CLI
I hope it will help you.
Good luck!