Search code examples
javaexceptionprocessbuilder

How to verify if external process terminated abnormally?


Following code snippet runs external process:

ProcessBuilder pb = new ProcessBuilder("C:\\Program Files\\Java\\jdk1.8.0_111\\bin\\java.exe", 
                "-cp",
                "D:\\nsd-rest\\target\\classes",
                "com.dataart.ExternalProcess"); //java -cp D:\nsd-rest\target\classes my.package.ExternalProcess
Process process = pb.start();
System.out.println(process.waitFor(10, TimeUnit.SECONDS)); // prints true

The external process looks like this:

public class ExternalProcess {
    public static void main(String[] args) { 
       throw new RuntimeException();
    }
}

The first snippet prints true despite exception throwns from external process.

Is there way to verify that if process finished abnormally ?


Solution

  • From the Process#waitFor(long timeout, TimeUnit unit) Javadoc

    Returns: true if the subprocess has exited and false if the waiting time elapsed before the subprocess has exited.

    You can use the Process#exitValue() to retrieve the exit value, and check if it's != 0

    Returns: the exit value of the subprocess represented by this Process object. By convention, the value 0 indicates normal termination.