如何使用javas Process.waitFor()?

编程入门 行业动态 更新时间:2024-10-28 01:12:33
本文介绍了如何使用javas Process.waitFor()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试从Java运行命令行命令,快速的健全性检查让我意识到我遇到麻烦的原因是我无法获得 pr.waitFor()请致电以下工作。这个程序在不到30秒后结束,并且在foo:之后不打印任何内容。我预计它需要超过30秒并在foo:之后打印一个随机数。我究竟做错了什么?

I am trying to run command line commands from Java and a quick sanity check made me realize that the reason I am having trouble is that I can't get the pr.waitFor() call below to work. This programs ends in less than 30s and prints nothing after "foo:". I expected it to take just over 30 s and print a random number after "foo:". What am I doing wrong?

import java.io.BufferedReader; import java.io.InputStreamReader; public class Sample { public static void main(String[] args) throws Exception { Runtime rt = Runtime.getRuntime(); Process pr = rt.exec("sleep 32; echo $RANDOM"); pr.waitFor(); BufferedReader input = new BufferedReader( new InputStreamReader(pr.getInputStream())); String line=null; StringBuilder s = new StringBuilder(); while((line=input.readLine()) != null) { System.out.println(s); s.append(line); } System.out.println("foo: " + s.toString()); } }

推荐答案

你应该尝试这个:

Process pr = rt.exec(new String[]{ "bash","-c", "sleep 32; echo $RANDOM" });

这将启动一个shell进程,然后在shell中运行你的命令。在命令完成之后,shell才会返回。

This launches a shell process and then within the shell runs your commands. The shell doesn't return till AFTER the commands have completed.

请告诉我这是否适合您。

Let me know if that works for you.

更多推荐

如何使用javas Process.waitFor()?

本文发布于:2023-10-30 03:01:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1541568.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   javas   waitFor   Process

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!