Java程序执行命令需要很长时间 [英] Java program to execute a command taking a long time
问题描述
我已经阅读了许多示例,最后使用以下代码从Java程序内部执行命令行命令。
I have read many examples and ended up using the following code to execute a command line command from inside of a Java program.
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);
}
}
}
simple ls命令和它工作正常。当我尝试运行另一个命令,它是永远的(保持运行25分钟,并没有停止)。
I have tested it with a simple ls command and it works fine. When I try to run another command, it is taking forever (kept running for 25 minutes and did not stop yet).
当我在命令行执行tabix命令时,得到以下统计信息:
When I execute a tabix command on the command line, I get the following statistics
4.173u 0.012s 0:04.22 99.0%0 + 0k 0 + 0io 0pf + 0w
4.173u 0.012s 0:04.22 99.0% 0+0k 0+0io 0pf+0w
命令是
time tabix文件pos1 pos2 ... pos190> / dev / null
time tabix file pos1 pos2 ... pos190 > /dev/null
问题是tabix命令包含 / dev / null
到底?
Could the problem be that the tabix command includes > /dev/null
at the end? If not, what could cause this issue?
推荐答案
您需要在之前将读者附加到该过程调用它的 waitFor
。没有它,可以填充它的分配的输出缓冲区然后阻止 - 但只有对于大输出,小(例如测试)输出将似乎很好。
You need to attach the reader to the process before calling it's waitFor
. Without that it could fill it's allocated output buffer and then block - but only for big output, small (e.g. test) output will seem to be fine.
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");
}
这篇关于Java程序执行命令需要很长时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!