【发布时间】:2014-05-24 19:26:44
【问题描述】:
我在 OSX 10.8.5 上并尝试从 Java 运行终端命令。
因此,使用下面的代码,我可以读取 Runtime.getRuntime().exec 的某些命令的输出,但不能读取其他命令。
你会看到一些命令像 ls 和 ifconfig 一样返回它们的输出,但是尝试让 openssl 返回它的输出要么什么也不返回,要么挂起,具体取决于实现。
我还使用了两种不同的方法来读取输出,但结果相同。
是什么阻止了某些命令返回任何输出?
theCommand = "ls"; //this command works OK and returns its output
//theCommand = "ifconfig"; //this command works OK and returns its output
//theCommand = "openssl rand"; //this command does not return any output
//theCommand = "/bin/sh openssl rand"; //this command does not return any output
//theCommand = "/bin/sh -c openssl rand"; //this command hangs
try {
System.out.println("trying...");
Process extProc=Runtime.getRuntime().exec(theCommand);
extProc.waitFor();
//READ ouput attempt #1 - this works okay for ls and ifconfig command
//BufferedReader readProc=new BufferedReader(new InputStreamReader(extProc.getInputStream()));
//while(readProc.ready()) {
// theReadBuffer = readProc.readLine();
// System.out.println(theReadBuffer);
//}
//READ output attempt #2 - this works okay for ls and ifconfig command
InputStream theInputStream = extProc.getInputStream();
java.util.Scanner theScanner = new java.util.Scanner(theInputStream).useDelimiter("\\A");
if (theScanner.hasNext()) {
theReadBuffer = theScanner.next();
System.out.println(theReadBuffer);
}
} catch( IOException e) {
System.out.println(e.getMessage());
} catch(InterruptedException e) {
System.out.println(e.getMessage());
}
我最终试图从这个命令(在终端中工作)生成随机字符:
openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//'
谢谢
【问题讨论】:
-
尝试使用 ProcessBuilder,并在执行前显式设置进程的 redirectErrorStream 选项。可能是进程正在写入 STDErr。
-
是的,感谢这有帮助,因为问题是它正在写入 getErrorStream 而不是 getInputStream。
标签: java linux macos bash terminal