java 在java中确定使用运行时环境创建的进程是否已完成执行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6873830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:41:09  来源:igfitidea点击:

In java determine if a process created using Runtime environment has finished execution?

javaruntime.exec

提问by devashish jasani

Runtime.getRuntime.exex("abc.exe -parameters");

using .waitFor()does not help to determine the completion of process.

using.waitFor()无助于确定过程的完成。

回答by ericsoco

Looks like JDK8 introduces Process.isAlive(). Surprised it took so long...

看起来 JDK8 引入了Process.isAlive(). 没想到用了这么久……

In the meantime, the best option seems to be to poll Process.exitValue(), wrapped in a try-catch:

与此同时,最好的选择似乎是 poll Process.exitValue(),包裹在 try-catch 中:

// somewhere previous...
String[] cmd = { "abc.exe", "-p1", "-p2" };
Process process = Runtime.getRuntime.exec(cmd);

// call this method repeatedly until it returns true
private boolean processIsTerminated () {
    try {
        process.exitValue();
    } catch (IllegalThreadStateException itse) {
        return false;
    }
    return true;
}

Alternately, a similar method could return the exit value if the process had terminated, or some other specified value if not.

或者,如果进程终止,类似的方法可以返回退出值,否则返回其他指定值。

回答by Stephen C

Process.waitFor()(javadoc) shouldwork. If it doesn't work then either:

Process.waitFor()( javadoc)应该可以工作。如果它不起作用,那么要么:

  • there's a bug in the JVM or the OS (highly unlikelyfor something like this), or

  • there is something about the process and/or your Java code that means that the process won'texit.

  • JVM 或操作系统中存在错误(这种情况极不可能),或者

  • 进程和/或您的 Java 代码有一些东西意味着进程不会退出。



In current releases of Java you can also use Process.isAlive(javadoc) to test the process status without blocking until it finishes. For Java 7 and older there is a hacky solution that entails polling the process return code and catching an exception, but this is inefficient. You should upgrade to Java 8 or later as soon as possible!

在 Java 的当前版本中,您还可以使用Process.isAlive( javadoc) 来测试进程状态,而不会阻塞直到它完成。对于 Java 7 及更早版本,有一个 hacky 解决方案,需要轮询进程返回代码并捕获异常,但这是低效的。您应该尽快升级到 Java 8 或更高版本!



Once the task is finished its goes for an indefinite wait. (I don't know why).

一旦任务完成,它就会无限期地等待。(我不知道为什么)。

If this happening, then neither waitFor()or isAlive()will help.

如果发生这种情况,那么两者都不会waitFor()isAlive()不会有帮助。

The most likely reasons that a process launched from Java won't / can't exit are:

从 Java 启动的进程不会/不能退出的最可能原因是:

  • the process is blocked waiting for your Java application to give it some input (via its stdin),

  • the process is blocked waiting for your Java application to read its output (i.e. its stdout or stderr),

  • it is blocked waiting on some external event; e.g. if it is trying to talk remote server that is not responding,

  • something has sent it a STOP signal of some kind, or

  • it is just taking a looongtime to run.

  • 该进程被阻塞,等待您的 Java 应用程序为其提供一些输入(通过其标准输入),

  • 该进程被阻塞,等待您的 Java 应用程序读取其输出(即其 stdout 或 stderr),

  • 它被阻塞等待一些外部事件;例如,如果它试图与没有响应的远程服务器通话,

  • 有什么东西向它发送了某种停止信号,或者

  • 它只是采取looong的时间来运行。

The first two of these reasons / causes can be addressed by (respectively) closing the Java output stream connected to its standard input, and reading (and possibly discarding) the Java input streams connected to its standard output and standard error. The other causes are intractable, and your only options are to "wait it out" or attempt to kill off the process.

这些原因/原因中的前两个可以通过(分别)关闭连接到其标准输入的 Java 输出流,并读取(并可能丢弃)连接到其标准输出和标准错误的 Java 输入流来解决。其他原因是棘手的,您唯一的选择是“等待”或尝试终止进程。



Bottom line - you need to find out why your process isn't completing. The blocked Process.waitFor()call is a symptom, not the disease.

底线 - 您需要找出您的流程未完成的原因。阻塞的Process.waitFor()呼叫是一种症状,而不是疾病。

回答by Essej

I have a similar issue and neither of the methods written here works for me. This is my code:

我有一个类似的问题,这里写的方法都不适合我。这是我的代码:

public void startCCleaner() {
    System.out.println("Starting ccleaner...");
    try {
        Process process = new ProcessBuilder("C:\Program Files\CCleaner\CCleaner64.exe").start();
        if(process.waitFor() == 0 ){
            System.out.println("Process terminated ");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

回答by Hunter McMillen

If you don't want to use waitFor(), which apparently you don't you can always test the exit value directly.

如果您不想使用waitFor(),显然您不想使用,您可以随时直接测试退出值。

import java.util.*;
import java.io.*;
public class ProcExitTest
{
    public static void main(String args[])
    {
        try
        {            
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("<....>");
            int exitVal = proc.exitValue();
            System.out.println("Process exitValue: " + exitVal);
        } 
          catch (InterruptedException ie)
          {
            ie.printStackTrace();
          }
    }
}

exit code 0 means normal termination.

退出代码 0 表示正常终止。