King Dedede
King Dedede

Reputation: 1010

Using AWS CLI from batch script appears to prevent Process.waitFor from completing

I am trying to run AWS-CLI from a batch script to sync files with S3, then automatically close the cmd window.

In all my batch scripts without AWS-CLI involved the Process.waitFor method will cause the cmd window to automatically exit upon process execution completion, but this is not the case when I have an AWS CLI command in there.

The S3 Sync will finish and I will be left with an open cmd window, and the program will not continue until I manually close it.

Is there something special I need to do in order to make Process.waitFor work in this case, or otherwise automatically close the cmd window upon script completion?

This question is unique because the command normally returns just fine, but is not in the specific case of using AWS CLI.

Upvotes: 0

Views: 646

Answers (1)

teppic
teppic

Reputation: 7286

You're probably not reading the process output, so it's blocked trying to write to stdout.

This works for me:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.CompletableFuture;

public class S3SyncProcess {

    public static void main(String[] args) throws IOException, InterruptedException {
        // sync dir
        Process process = Runtime.getRuntime().exec(
            new String[] {"aws", "s3", "sync", "dir", "s3://my.bucket"}
        );

        CompletableFuture.runAsync(() -> pipe(process.getInputStream(), System.out));
        CompletableFuture.runAsync(() -> pipe(process.getErrorStream(), System.err));

        // Wait for exit
        System.exit(process.waitFor());
    }

    private static void pipe(InputStream in, OutputStream out) {
        int c;
        try {
            while ((c = in.read()) != -1) {
                out.write(c);
            }
        } catch (IOException e) {
            // ignore
        }
    }

}

Upvotes: 1

Related Questions