【问题标题】:Java program to execute a command taking a long timeJava程序执行命令需要很长时间
【发布时间】:2014-10-01 20:38:43
【问题描述】:

我阅读了很多示例,最终使用以下代码从 Java 程序内部执行命令行命令。

public static void executeCommand(final String command) throws IOException, 
    InterruptedException {
        System.out.println("Executing command " + command);
        final Runtime r = Runtime.getRuntime();
        final Process p = r.exec(command);
        System.out.println("waiting for the process");
        p.waitFor();
        System.out.println("waiting done");
        try (final BufferedReader b = new BufferedReader(new InputStreamReader(
            p.getInputStream()))) {
            String line;

            while ((line = b.readLine()) != null) {
                System.out.println(line);
            }
        }
    }

我已经用一个简单的 ls 命令对其进行了测试,它运行良好。当我尝试运行另一个命令时,它需要很长时间(保持运行 25 分钟并且还没有停止)。

当我在命令行执行 tabix 命令时,我得到以下统计信息

4.173u 0.012s 0:04.22 99.0% 0+0k 0+0io 0pf+0w

因此它应该很快完成。

命令是

时间 tabix 文件 pos1 pos2 ... pos190 > /dev/null

问题可能是 tabix 命令最后包含> /dev/null 吗?如果不是,什么可能导致此问题?

【问题讨论】:

  • 什么是“永远”?您是否尝试过其他命令,既简单又困难?可能会有额外的延迟,具体取决于命令中的内容。
  • 更多细节,请。您正在运行的确切命令是什么?直接运行命令的时间是多少,刚刚执行这个命令然后终止的public static void main的时间是多少?
  • 命令已经运行了14分钟,还在运行。
  • 命令基本上是时间 tabix 文件 pos1 pos2 pos3 ... pos190 > /dev/null
  • 您需要将阅读器附加到进程之前调用它为waitFor。没有它,它会填充它分配的输出缓冲区,然后阻塞 - 但仅适用于大输出,小输出似乎没问题。

标签: java optimization command-line


【解决方案1】:

您需要将阅读器附加到进程之前调用它为waitFor。没有它可以填充它分配的输出缓冲区然后阻塞 - 但仅用于大输出,小(例如测试)输出似乎没问题。

public static void executeCommand(final String command) throws IOException, InterruptedException {
    System.out.println("Executing command " + command);
    // Make me a Runtime.
    final Runtime r = Runtime.getRuntime();
    // Start the command process.
    final Process p = r.exec(command);
    // Pipe it's output to System.out.
    try (final BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
        String line;

        while ((line = b.readLine()) != null) {
            System.out.println(line);
        }
    }
    // Do this AFTER you've piped all the output from the process to System.out
    System.out.println("waiting for the process");
    p.waitFor();
    System.out.println("waiting done");
}

【讨论】:

  • 谢谢,这救了我!
猜你喜欢
  • 2018-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-19
  • 1970-01-01
  • 2014-05-12
  • 2012-12-03
  • 2011-03-14
相关资源
最近更新 更多