1

I want to run a jar script from within a Java program. The command is tested to run without problems if pasted sloley to the Windows cmd. However, my Java script stucks at p.waitFor().

public class MyClass{

   public static void main(String[] args) {

     try {
       // create a new process
       System.out.println("Creating Process...");
       Process p = Runtime.getRuntime().exec("U:\\locallib\\jdk-8u65-windows-x64\\tools\\bin\\java.exe -Xmx4g -jar U:\\path\\to\\my.jar arg1 arg2");
       System.out.println("Process is running...");

       p.waitFor();
       System.out.println("Process is terminated...");
     } 
     catch (Exception ex) {
       ex.printStackTrace();
     }
   }
}

Ouput:

Creating Process...
Process is running...

...and nothing else.

corinna
  • 629
  • 7
  • 18
  • Can you see it still running in the task manager? Does it wait for input or anything like that? – f1sh Apr 22 '16 at 11:05
  • It's listed, but seems to sleep. ...and it doesn't require input if running sloley in the Windows cmd. – corinna Apr 22 '16 at 11:12
  • i think you dont have a problem with the code – Priyamal Apr 22 '16 at 11:12
  • The jar script writes to STDOUT. Might that cause the problem? – corinna Apr 22 '16 at 11:13
  • 2
    You generally need to read the Process getInputStream (and also the getErrorStream), if you don't the program may become blocked when the buffers become full. – greg-449 Apr 22 '16 at 11:32
  • If you don’t want to read the output of the sub-process, you can redirect it to you own stdout using a `ProcessBuilder` and `inheritIO`, as shown [here](http://stackoverflow.com/a/19658154/2711488). – Holger Apr 22 '16 at 13:03
  • See also [When Runtime.exec() won't](http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html) for many good tips on creating and handling a process correctly. Then ignore it refers to `exec` and use a `ProcessBuilder` to create the process. – Andrew Thompson Apr 23 '16 at 02:46

0 Answers0