How to make child process die after parent exits?

后端 未结 24 1737
天涯浪人
天涯浪人 2020-11-22 05:31

Suppose I have a process which spawns exactly one child process. Now when the parent process exits for whatever reason (normally or abnormally, by kill, ^C, assert failure o

24条回答
  •  广开言路
    2020-11-22 06:13

    Even though 7 years have passed I've just run into this issue as I'm running SpringBoot application that needs to start webpack-dev-server during development and needs to kill it when the backend process stops.

    I try to use Runtime.getRuntime().addShutdownHook but it worked on Windows 10 but not on Windows 7.

    I've change it to use a dedicated thread that waits for the process to quit or for InterruptedException which seems to work correctly on both Windows versions.

    private void startWebpackDevServer() {
        String cmd = isWindows() ? "cmd /c gradlew webPackStart" : "gradlew webPackStart";
        logger.info("webpack dev-server " + cmd);
    
        Thread thread = new Thread(() -> {
    
            ProcessBuilder pb = new ProcessBuilder(cmd.split(" "));
            pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
            pb.redirectError(ProcessBuilder.Redirect.INHERIT);
            pb.directory(new File("."));
    
            Process process = null;
            try {
                // Start the node process
                process = pb.start();
    
                // Wait for the node process to quit (blocking)
                process.waitFor();
    
                // Ensure the node process is killed
                process.destroyForcibly();
                System.setProperty(WEBPACK_SERVER_PROPERTY, "true");
            } catch (InterruptedException | IOException e) {
                // Ensure the node process is killed.
                // InterruptedException is thrown when the main process exit.
                logger.info("killing webpack dev-server", e);
                if (process != null) {
                    process.destroyForcibly();
                }
            }
    
        });
    
        thread.start();
    }
    

提交回复
热议问题