Question

I have a java program that is supposed to run a bat file, and then exit with a success code 0.

The code essentially looks like this

Runtime.exec(....);

System.exit(0);

99.8% of the time, this works perfectly. But very sporadically the bat file won't get run.

My theory is that on certain systems, the Runtime.exec can't finish its spawning before the System.exit runs. Is this likely/possible?

I looked at the source of Runtime.exec but it drops into native code to do the interesting stuff.

EDIT

Based on the answers so far, I should state that the .bat file executes another java process using javaw. I can confirm that the 1st java process ending does NOT kill the 2nd one run in the bat file.

Is it possible that when the problem happens the bat file hadn't spawned the 2nd java process before the System.exit occurred? Perhaps it is not a Runtime.exec problem after all?

EDIT2

I cannot wait for the 2nd process to end, it could run indefinitely and my 1st process must exit.

Was it helpful?

Solution

You are creating a child process that will terminate with its parent. You must use Process.waitFor in Java to ensure that Java process waits for the bat process to finish.

OTHER TIPS

Try to change to ProcessBuilder. Maybe it works better.

System.exit(0) kills jvm instance. All process will be terminated. If you want to really execute System.exit(0), make sure exec process is done before calling System.exit.

Use Process.waitFor(), the return type of this method is int which gives you the return code as per your current solution using Runtime.
waitFor() causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.

Change it to

Runtime.getRuntime().exec(....).waitFor();

System.exit(0);

But then this will wait for batch file to complete execution and in your case completion of javaw instance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top