简体   繁体   中英

Batch file immediately terminates after executing a Java program (if batch file is called from another Java program)

I have a batch file called 'StartUpdate.bat' which contains something like this:

set CLASSPATH="myclasspath"
java -cp %CLASSPATH% UpdateProgram
runMyApp.bat

If I run 'StartUpdate.bat' directly from command line, it executes UpdateProgram and then runMyApp.bat immediately after. This is the intention.

However, if I call 'StartUpdate.bat' from another Java program, it terminates immediately after completing UpdateProgram. 'StartUpdate.bat' is called from this other Java program using

Runtime.getRuntime().exec(path + "StartUpdate.bat");

StartUpdate.bat is executed just fine, as is UpdateProgram inside it, but nothing else following UpdateProgram.

Why does it behave this way? What should I do so that it executes the remainder of the batch file?

您可以使用调用开始执行java程序

Explicitly use a user Thread with setDaemon(false) . It seems that there was the problem.

As long as there is a user (non-daemon) thread, the JVM will keep the application alive. Daemon threads are closed when no user threads exist anymore.

As daemon threads are typically used for such "server" like purposes, an often misconception.

For the rest ProcessBuilder would be a more robust class for this task.

ProcessBuilder pb = new ProcessBuilder("dir");
Process process = pb.start();
int returnCode = process.waitFor();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM