Search code examples
javaswingjarsystem.exit

Running Java program by a Java program


I am making a program (3D Minesweeper) and I'm having problems with detecting the result. I tried separate Thread to wait for the result, but it doesn't work(just no). So I figured the simplest way would be having 2 separate programs (not a problem), where one runs the other (with args,1.problem) and gets the value returned by it's System.exit();(2.problem). I've found some examples of solving the first problem, but not the second. Is there a proper way to do it, or do I have to write the result to a file or something? BTW feel free to correct grammar, I'm just learning XD.


Solution

  • If you are using System.exec () to run the programs, then look at the return value of waitFor () for the Process

    Process p = Runtime.getRuntime().exec("cmd /C dir");
    int rc = p.waitFor ();
    System.out.println ("Exit code is " + rc);
    

    You can also look at the exitValue () of the process, but you have to be sure the program has run to completion before this is reliable.

    Process p = Runtime.getRuntime().exec("cmd /C dir");
    p.waitFor (); // make sure we run to completion
    System.out.println ("Exit code is " + p.exitValue ());