开发者

How to use javas Process.waitFor()?

开发者 https://www.devze.com 2023-03-09 13:18 出处:网络
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

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


You should try this:

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

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.


Process.waitFor() blocks the current thread until the process has terminated, at which point the execution control returns to the thread that spawned the process.

In the posted code, once the process has terminated (i.e., after the Process.waitFor invocation), the input stream of the now terminated process no longer has any data that can be read. Reading the contents of the stream and printing it out, will therefore not result in any tangible input.

If you need to read the contents of the stream, you'll need to spawn a new thread that will take care of the necessary activities of reading the input stream and writing to the output stream as required, before the child process terminates.

Or you could perform the reading and writing in the same thread, but before you wait for the child process to terminate. In other words, you'll need to switch the sequence of the lines containing pr.waitFor(); and the lines that read from the InputStream.

Related question on SO:

  1. Process.waitFor(), threads, and InputStreams


You are trying to execute shell commands. You should try to execute a program.

As shown in Femi's answer you could invoke bash as the executable and then pass to it arguments that will have bash execute the sleep and echo command.

0

精彩评论

暂无评论...
验证码 换一张
取 消