如何在java中运行async bash命令



我正试图从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()

最新更新