简体   繁体   中英

Java Runtime.exec() asynchronous output

I'd like to get the output from a long running shell command as it is available instead of waiting for the command to complete. My code is run in a new thread

Process proc = Runtime.getRuntime().exec("/opt/bin/longRunning");
InputStream in = proc.getInputStream();
int c;
while((c = in.read()) != -1) {
    MyStaticClass.stringBuilder.append(c);
}

The problem with this is that my program in /opt/bin/longRunning has to complete before the InputStream gets assigned and read. Is there any good way to do this asynchronously? My goal is that an ajax request will return the current value MyStaticClass.stringBuilder.toString() every second or so.

I'm stuck on Java 5, fyi.

Thanks! W

Try with Apache Common Exec . It has the ability to asynchronously execute a process and then "pump" the output to a thread. Check the Javadoc for more info

Runtime.getRuntime().exec does not wait for the command to terminate, so you should be getting the output straight away. Maybe the output is being buffered because the command knows it is writing to a pipe rather than a terminal?

Put the reading in a new thread:

new Thread() {
    public void run() {
        InputStream in = proc.getInputStream();
        int c;
        while((c = in.read()) != -1) {
            MyStaticClass.stringBuilder.append(c);
        }
    }
}.start();

Did you write the program you're calling? If so try flushing your output after writing. The text could be stuck in a buffer and not getting to your java program.

I use this code to do this and it works:

    Runtime runtime = Runtime.getRuntime();
    Process proc = runtime.exec(command);
    BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));

    while (true) {

        // enter a loop where we read what the program has to say and wait for it to finish
        // read all the program has to say
        while (br.ready()) {
            String line = br.readLine();
            System.out.println("CMD: " + line);
        }

        try {
            int exitCode = proc.exitValue();
            System.out.println("exit code: " + exitCode);
            // if we get here then the process finished executing
            break;
        } catch (IllegalThreadStateException ex) {
            // ignore
        }

        // wait 200ms and try again
        Thread.sleep(200);

    }

Try :

   try {  
         Process p = Runtime.getRuntime().exec("/opt/bin/longRunning");  
         BufferedReader in = new BufferedReader(  
                                    new InputStreamReader(p.getInputStream()));  
         String line = null;  
         while ((line = in.readLine()) != null) {  
         System.out.println(line);  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM