【问题标题】:How to run async bash command in java?如何在java中运行异步bash命令?
【发布时间】:2020-04-24 19:26:59
【问题描述】:

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

谢谢!!!

【问题讨论】:

  • 出了什么问题:你说你正在尝试这个命令。但是你不说怎么回事? (似乎)什么都没有发生吗?您是否收到错误消息/代码? bash 命令运行但做错了吗?
  • 代码格式化,添加标签
  • 命令已执行但java代码不等待它完成

标签: java bash asynchronous concurrency execution


【解决方案1】:

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

【讨论】:

  • 我收到此错误:cannot find symbol symbol: method onExit() location: class java.lang.Process 我假设我不使用 Java 9+?
  • 我没有运行 Java 9+ 但.waitFor() 为我解决了这个问题,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-17
  • 2021-01-29
  • 1970-01-01
  • 1970-01-01
  • 2013-11-02
  • 1970-01-01
相关资源
最近更新 更多