简体   繁体   English

批处理文件在执行Java程序后立即终止(如果从另一个Java程序调用了批处理文件)

[英]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: 我有一个名为“ StartUpdate.bat”的批处理文件,其中包含以下内容:

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. 如果我直接从命令行运行“ StartUpdate.bat”,它将执行UpdateProgram,然后立即运行MyApp.bat。 This is the intention. 这是意图。

However, if I call 'StartUpdate.bat' from another Java program, it terminates immediately after completing UpdateProgram. 但是,如果我从另一个Java程序调用“ StartUpdate.bat”,则它在完成UpdateProgram后立即终止。 'StartUpdate.bat' is called from this other Java program using 使用此其他Java程序调用“ StartUpdate.bat”

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

StartUpdate.bat is executed just fine, as is UpdateProgram inside it, but nothing else following UpdateProgram. StartUpdate.bat和其中的UpdateProgram一样可以很好地执行,但在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) . 使用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. 只要有一个用户(非守护程序)线程,JVM就会使该应用程序保持活动状态。 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将是此任务更强大的类。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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