How can I cause a child process to exit when the parent does?

后端 未结 9 1878
一生所求
一生所求 2020-11-27 16:07

I am launching a child process with ProcessBuilder, and need the child process to exit if the parent process does. Under normal circumstances, my code is stopping the child

相关标签:
9条回答
  • 2020-11-27 16:38

    Try to send a kill signal to the child process from the parent when the parent stops

    0 讨论(0)
  • 2020-11-27 16:46

    For windows, I came up with this polling hack:

    static int getPpid(int pid) throws IOException {
        Process p = Runtime.getRuntime().exec("C:\\Windows\\System32\\wbem\\WMIC.exe process where (processid="+pid+") get parentprocessid");
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        br.readLine();
        br.readLine();
        String ppid= br.readLine().replaceAll(" ","");
        return Integer.parseInt(ppid);
    }
    static boolean shouldExit() {
        try {
            String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
            int ppid = getPpid(Integer.parseInt(pid));
            /* pppid */ getPpid(ppid);
        } catch (Exception e) {
            return true;
        } 
        return false;
    }
    
    0 讨论(0)
  • 2020-11-27 16:48

    For a single child processes you can manage this by inverting the child/parent relationship. See my answer to a later incarnation of this question.

    0 讨论(0)
提交回复
热议问题