微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

突然关闭时关闭系统创建的所有进程

如何解决突然关闭时关闭系统创建的所有进程

我的 Java 程序启动了其他几个 Java 进程。当程序关闭时,所有创建的进程都应该终止。

如果程序通过内部停止命令停止,则可以保存所有数据并关闭进程。我为此使用了关闭挂钩,到目前为止效果很好。

但是如果程序突然终止或用户没有正确关闭,所有进程都会继续运行并且程序在下次启动时无法运行。

如何才能在程序突然停止时执行代码,或者更确切地说,如何停止进程?

按照建议,我应该包含一些代码。这是代码简化版本:

启动进程的类:

@Override
public void startProcess() throws IOException {

    String command = "java -jar server.jar nogui";
    this.process = Runtime.getRuntime().exec(command,null,new CloudFolder(super.getPath()).get());

    final InputReader reader = new InputReader();
    reader.open();

    String in = reader.getinput();

    if (in.equals("stop")) {

        this.process.destroy();
        this.process.getoutputStream().close();

    }
}

主类:

public static void main(String[] args) {
    
    // normally the startProcess() Method would be
    // called right here.

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            
            // Just to see if it worked
            File file = new File("closing");
            try {
                file.createNewFile();
            } catch (IOException exception) {
                exception.printstacktrace();
            }
            
        }
    },"Shutdown-thread"));

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。