我有一个场景,我需要终止一个 java 进程。
这是我的场景:
我在那个 web 应用程序中有 web 应用程序我已经实现了一个 Listener
类,如下所示
public class MyListener extends ServletContextListener {
java.lang.Process ps = null;
public void contextInitialized(ServletContextEvent arg0) {
// This will be excuted when my web application executed
String command= "cmd.exe start maybatch";// This command is to execute a batch program that triggers java program
ps = Runtime.getRunTime().exec(command);
}
public void contextDestroyed(ServletContextEvent arg0) {
//This part will be executed when server shutdown happens.
// Here I want to close the java process which was triggered when project deployed.
if( ps !=null)
ps.destroy();
}
}
我的要求是在我的 tomcat 关闭时关闭 Java 进程,并在我的 web 应用程序部署时启动 java 程序。
一切正常,直到在部署项目时启动 java 进程。
但是我不知道如何关闭部署时触发的java进程
如有任何帮助,我们将不胜感激。 提前致谢。
抱歉不清楚..
mybatch
启动一个新的 java 程序
。
最佳答案
首先,如果您想了解 Web 应用程序的关闭并终止您的子进程,您应该在代码片段中使用 contextDestroyed() 方法而不是 contextInitialized()。 所以基本上你需要交换你的方法的内容。
public class MyListener extends ServletContextListener {
java.lang.Process ps = null;
public void contextInitialized(ServletContextEvent arg0) {
// This will be excuted when my web application executed
String command= "cmd.exe start maybatch";// This command is to execute a batch program that triggers java program
ps = Runtime.getRunTime().exec(command);
}
public void contextDestroyed(ServletContextEvent arg0) {
//This part will be executed when server shutdown happens.
// Here I want to close the java process which was triggered when project deployed.
if( ps !=null)
ps.destroy();
}
}
}
UPD
您是否可以避免使用批处理文件? 如果是,您将能够关闭生成的 Java 应用程序。 PS 我发现此链接非常有用:
Start a java process (using Runtime.exec / ProcessBuilder.start) with low priority?
关于java - 如何用java程序杀死一个java程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27165644/