从 Java 执行 shell 命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3062305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Executing shell commands from Java
提问by Lauren?iu Dasc?lu
I'm trying to execute a shell command from a java application, on the GNU/Linux platform. The problem is that the script, that calls another java application, never ends, although it runs successfully from bash. I tried to debug it:
我正在尝试从 GNU/Linux 平台上的 Java 应用程序执行 shell 命令。问题是调用另一个 java 应用程序的脚本永远不会结束,尽管它从 bash 成功运行。我试图调试它:
(gdb) bt #0 0xb773d422 in __kernel_vsyscall () #1 0xb7709b5d in pthread_join (threadid=3063909232, thread_return=0xbf9cb678) at pthread_join.c:89 #2 0x0804dd78 in ContinueInNewThread () #3 0x080497f6 in main ()
I tried with: ProcessBuilder(); and Runtime.getRuntime().exec(cmd);
我试过: ProcessBuilder(); 和 Runtime.getRuntime().exec(cmd);
Looks like it waits for something to finish. Any ideas?
看起来它在等待某事完成。有任何想法吗?
Thanks, Lauren?iu
谢谢,劳伦?iu
采纳答案by dsmith
Are you processing the standard input and standard output? From the javadocs:
你在处理标准输入和标准输出吗?从javadocs:
Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.
由于一些原生平台只为标准输入输出流提供有限的缓冲区大小,如果不能及时写入输入流或读取子进程的输出流,可能会导致子进程阻塞,甚至死锁。
Process cmdProc = Runtime.getRuntime().exec(command);
BufferedReader stdoutReader = new BufferedReader(
new InputStreamReader(cmdProc.getInputStream()));
String line;
while ((line = stdoutReader.readLine()) != null) {
// process procs standard output here
}
BufferedReader stderrReader = new BufferedReader(
new InputStreamReader(cmdProc.getErrorStream()));
while ((line = stderrReader.readLine()) != null) {
// process procs standard error here
}
int retValue = cmdProc.exitValue();