【问题标题】:Java executes command but the value is not returnedJava执行命令但没有返回值
【发布时间】:2020-06-11 12:53:26
【问题描述】:

PHP 调用 shell 脚本,shell 脚本调用另一台服务器上的 cronjob。

我目前正在将相同的业务逻辑转换为 Java。

但是,当我们使用 Java 的“运行时”进行开发时,该服务器的 cronjob 会报告 (defunct)

WaitFor()网页屏幕也在不断等待方法

我该怎么办?

public Map execCommand(String... str) {
    Map<Integer, String> map = new HashMap<>();
    ProcessBuilder pb = new ProcessBuilder(str);
    pb.redirectErrorStream(true);
    Process process = null;
    try {
        process = pb.start();
    } catch (IOException e) {
        e.printStackTrace();
    }

    BufferedReader reader = null;
    if (process != null) {
        reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    }

    String line;
    StringBuilder stringBuilder = new StringBuilder();
    try {
        if (reader != null) {
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        if (process != null) {
            process.waitFor();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    if (process != null) {
        map.put(0, String.valueOf(process.exitValue()));
    }

    try {
        map.put(1, stringBuilder.toString());
    } catch (StringIndexOutOfBoundsException e) {
        if (stringBuilder.toString().length() == 0) {
            return map;
        }
    }
    return map;
}

【问题讨论】:

  • 输出到stderr而不是stdout吗?

标签: java linux shell runtime.exec


【解决方案1】:

从输入流中读取之后 waitFor().

【讨论】:

    猜你喜欢
    • 2019-09-03
    • 2016-04-12
    • 2020-03-02
    • 2013-01-22
    • 1970-01-01
    • 2012-05-29
    • 2011-12-11
    • 2015-11-03
    • 1970-01-01
    相关资源
    最近更新 更多