从Java执行shell命令

前端之家收集整理的这篇文章主要介绍了从Java执行shell命令前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试从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 ()

我尝试过:ProcessBuilder();和Runtime.getRuntime().exec(cmd);

看起来它等待完成一些事情.有任何想法吗?

谢谢,
Laurenţiu

解决方法

您在处理标准输入和标准输出吗?从 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();
原文链接:https://www.f2er.com/java/128004.html

猜你在找的Java相关文章