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