我正在尝试从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()?
发布评论