gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:40:33 25 4
gpt4 key购买 nike

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

关于java - 如何在java中运行异步bash命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61416000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com