如何在Java中运行异步bash命令?

问题描述 投票:0回答:1

我正在尝试从Java文件运行异步bash命令,并等待其完成之后再继续执行Java代码。

此刻,我已经尝试像这样使用Callable

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";
        }
    }
}

而且我这样称呼它:

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

谢谢!

java bash asynchronous concurrency execution
1个回答
0
投票

更简单的方法是使用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.

如果仍然要阻止,请使用.waitFor()

© www.soinside.com 2019 - 2024. All rights reserved.