How to get shutdown hook to execute on a process launched from Eclipse

前端 未结 7 1527
天涯浪人
天涯浪人 2020-12-03 00:43

I have a shutdown hook in my application (created using Runtime.getRuntime().addShutdownHook). However if I launch the application from within Eclipse, when it

7条回答
  •  悲哀的现实
    2020-12-03 01:09

    On Windows to gracefully stop a java application in a standard way you need to send Ctrl + C to it. This only works with console apps, but Eclipse uses javaw.exe instead of java.exe. To solve this open the launch configuration, JRE tab and select "Alternative JRE:". The "Java executable" group box appears and allows to enter the alternate executable "java".

    Now we need an external program to send Ctrl-C to a process with a hidden console. I found hints here and here. Our program attaches to the console of the desired process and sends the console event.

    #include 
    #include 
    
    int main(int argc, char* argv[])
    {
        if (argc == 2) {
            unsigned pid = 0;
            if (sscanf_s(argv[1], "%u", &pid) == 1) {
                FreeConsole(); // AttachConsole will fail if we don't detach from current console
                if (AttachConsole(pid)) {
                    //Disable Ctrl-C handling for our program
                    SetConsoleCtrlHandler(NULL, TRUE);
                    GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
                    return 0;
                }
            }
        }
    
        return 1;
    }
    

    Test java program:

    public class Shuthook {
    
        public static void main(final String[] args) throws Exception {
            Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    System.out.println("Shutting down...");
                }
            });
    
            String sPid = ManagementFactory.getRuntimeMXBean().getName();
            sPid = sPid.substring(0, sPid.indexOf('@'));
    
            System.out.println("pid: " + sPid);
            System.out.println("Sleeping...");
            Thread.sleep(1000000);
        }
    
    }
    

    Terminating it:

    C:\>killsoft.exe 10520
    

    Test program output in Eclipse:

    pid: 10520
    Sleeping...
    Shutting down...
    

提交回复
热议问题