I've got some code that uses Runtime.exec() to run an external .jar (built as an IzPack installer).
If I run this external.jar from the command line like so:
java -jar external.jar
Then the command prompt does not return control until the application is finished. However, if I run external.jar from within some java class, using:
Process p = Runtime.getRuntime().exec("java -jar external.jar");
int exitCode = p.waitFor();
System.out.println("Process p returned: " + exitCode);
Then p
returns almost instantly with a success code of 0
, despite external.jar having not yet completed execution (i've also tried this via the ProcessBuilder
route of external file execution).
Why does it wait to return from the command line, but not when executed from within another java program?
I've also set up 3 jars, A, B and C where A calls B which calls C (using Runtime.exec()
), where C Thread.sleep
s for 10 seconds, as a simple test, and as expected, A doesn't return until 10 seconds after it runs.
I figure this is probably some kind of a threading issue with external.jar where execution is being handed over from one thing to another, but given that it works directly from the command line i kind of expected to see the same behaviour (perhaps naively) when called from within another java program.
I've tested this on Windows and Ubuntu with Java 6.
Thanks!
whatFor()
will wait for the the process you've started to end, meaning all non-daemon threads have finished, so I doubt that it's a threading issue alone. I wonder if the jar your calling itself calls an outside process and then exits. – Possessivenotify()
on yourProcess
field? That is whatwaitFor()
does inUNIXProcess
at least. – StudbookSystem.out.println
s of its own that log its execution process. This logging is still very much in continuation when the exit code is returned (plus, i know it takes a solid 30s or so to do everything whereas the return is almost instantaneous). Perhaps this ties into what Hovercraft is suggesting? – HoldProcess p
is completely self-contained within a method call that does nothing else beyond what's described above, so there's no other interaction with it. – Hold