Skip to content
Advertisement

How to run async bash command in java?

I’m trying to run an async bash command from a java file and wait for it to finish before I continue the java code execution.

At this moment I’ve tried using Callable like so:

class AsyncBashCmds implements Callable{

    @Override
    public String call() throws Exception {
        try {
            String[] cmd = { "grep", "-ir", "<" , "."};

            Runtime.getRuntime().exec(cmd); 

            return "true"; // need to hold this before the execution is completed.

        } catch (Exception e) {
            return "false";
        }
    }
}

and I call it like so:

ExecutorService executorService = Executors.newFixedThreadPool(1);
Future<String> future =  executorService.submit(new runCPPinShell(hookResponse));
String isFinishedRunningScript = future.get();

Thanks!!!

Advertisement

Answer

An easier way is to use Java 9+ .onExit():

private static CompletableFuture<String> runCmd(String... args) {
    try {
        return Runtime.getRuntime().exec(args)
            .onExit().thenApply(pr -> "true");
    } catch (IOException e) {
        return CompletableFuture.completedFuture("false");
    }
}

Future<String> future = runCmd("grep", "-ir", "<" , ".");
String isFinishedRunningScript = future.get(); // Note - THIS will block.

If you want to block anyway, use .waitFor().

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement