0

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!!!

3
  • What's going wrong: you say that you are trying the command. But you don't say what's going wrong? DOes (it appear that) nothing happens at all? Do you get an error message/code? Does the bash command run but do the wrong thing? Commented Apr 25, 2020 at 1:46
  • Code formating, tags added Commented Apr 25, 2020 at 14:54
  • the command is executed but the java code does not wait for it to finish Commented Apr 25, 2020 at 15:28

1 Answer 1

1

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().

Sign up to request clarification or add additional context in comments.

2 Comments

I get this error : cannot find symbol symbol: method onExit() location: class java.lang.Process I assume I do not use Java 9+ ?
I am not running Java 9+ but .waitFor() solved it for me, Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.