简体   繁体   English

从Java执行Shell命令

[英]Executing shell commands from Java

I'm trying to execute a shell command from a java application, on the GNU/Linux platform. 我正在尝试从GNU / Linux平台上的Java应用程序执行shell命令。 The problem is that the script, that calls another java application, never ends, although it runs successfully from bash. 问题是,尽管它可以从bash成功运行,但是调用另一个Java应用程序的脚本永远不会结束。 I tried to debug it: 我试图调试它:

(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(); 我尝试使用:ProcessBuilder(); and Runtime.getRuntime().exec(cmd); 和Runtime.getRuntime()。exec(cmd);

Looks like it waits for something to finish. 看起来它正在等待完成。 Any ideas? 有任何想法吗?

Thanks, Laurențiu 谢谢,Laurențiu

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM