运行时exec在ubuntu上

时间:2014-01-23 14:47:16

标签: java linux ubuntu

我尝试从java运行wavemon命令并读取输出。 但我无法使Runtime.exec方法有效。

注释中的echo命令工作并打印“hello”,但是wavemon命令只返回“”。已经安装了Wavemon,我甚至尝试使用它的完整路径(/ usr / bin / wavemon)作为参数。 什么都行不通。

// call wavemon
Runtime rt = Runtime.getRuntime();
String[] cmd = { "sh", "-c", "wavemon", "-i wlan1", "-d" };
//String[] cmd = { "sh", "-c","echo hello" };
Process proc = rt.exec(cmd);
proc.waitFor();

// read wavemon output into string
Scanner is =  new Scanner(new InputStreamReader(proc.getInputStream()));

StringBuffer buffer = new StringBuffer();
while (is.hasNext()) {
    buffer.append(is.nextLine());

}

proc.destroy();
System.out.println(buffer.toString());

wavemon命令的输出以空行开头,但由于我使用扫描仪,这不重要吗?

$ wavemon -i wlan1 -d

Configured device: wlan1 (IEEE 802.11abgn)
Security: WPA, WPA2, TKIP, CCMP
...

一点细节,这个代码用在Spring框架中(spring-boot,tomcat容器)。

1 个答案:

答案 0 :(得分:0)

你不应该需要“sh -c”。请尝试仅使用:

String[] cmd = { "wavemon", "-i","wlan1", "-d" };

此外,您应该在从扫描仪读取行后放置waitFor(),因为这样可以保留线程,直到完成该过程。但是,在您阅读输出之前,该过程可能无法完成。您可以获得更好的功能,并在不同的线程上读取所有流。

本文详细介绍了http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html