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

How to run async bash command in java?

我正在尝试 运行 来自 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 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()