How to use javas Process.waitFor()?

被刻印的时光 ゝ 提交于 2019-12-04 06:00:35

问题


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

回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/6177711/how-to-use-javas-process-waitfor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!