加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

从Java执行shell命令

发布时间:2020-12-15 02:51:18 所属栏目:Java 来源:网络整理
导读:我正在尝试从GNU / Linux平台上的Java应用程序执行shell命令.问题是调用另一个java应用程序的脚本永远不会结束,尽管它从bash成功运行.我试着调试它: (gdb) bt#0 0xb773d422 in __kernel_vsyscall ()#1 0xb7709b5d in pthread_join (threadid=3063909232,thr
我正在尝试从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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读