Ensure executables called in Go Process get killed when Process is killed

后端 未结 5 1601
庸人自扰
庸人自扰 2021-01-02 06:42

I have some code that in Go (golang), has a few different threads running a separate executable. I want to ensure that if a user kills my process in Go, that I have a way of

5条回答
  •  孤独总比滥情好
    2021-01-02 07:42

    One possible strategy is to keep a list of processes you're running in a global array var childProcesses = make([]*os.Process, 0) and append to it every time you start a process.

    Have your own Exit function. Make sure that you never call os.Exit anywhere in your code, and always call your own Exit function instead. Your Exit function will kill all the childProcesses

    for _, p := range childProcesses {
        p.Kill()
    }
    

    Handle signals so they go through your own exit function, for example by doing this during initialization (somewhere near the top of your main function)

    sigs := make(chan os.Signal, 1)
    signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL, syscall.SIGQUIT)
    goUnsafe(func() {
        var signal = <-sigs
        log.Println("Got Signal", signal)
        Exit(0)
    })
    

提交回复
热议问题