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

后端 未结 5 1590
庸人自扰
庸人自扰 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:36

    I would suggest you to use unix.Prctl.

    flag := unix.SIGHUP
    if err := unix.Prctl(unix.PR_SET_PDEATHSIG, uintptr(flag), 0, 0, 0); err != nil {
        return
    }
    

    A detailed example is below, new.go for child process and main.go as parent process.

    //new.go
    package main
    
    func main() {
        flag := unix.SIGHUP
    
        if err := unix.Prctl(unix.PR_SET_PDEATHSIG, uintptr(flag), 0, 0, 0); err != nil {
        return
        }
    
        f, _ := os.Create("./dat2")
        defer f.Close()
        i := 0
        for {
            n3, _ := f.WriteString("writes " + string(i) + "\n")
            fmt.Printf("wrote %d bytes\n", n3)
            f.Sync()
            i += 2
            time.Sleep(2 * time.Second)
        }
    
        for {
            n3, _ := f.WriteString("newwrites\n")
            fmt.Printf("wrote %d bytes\n", n3)
            f.Sync()
            time.Sleep(2 * time.Second)
        }
    }
    
    
    //main.go
    package main
    
    import "os/exec"
    
    func main() {
        commandA := exec.Command("./new")
        commandA.Start()
        commandB := exec.Command("./new")
        commandB.Start()
        for {
        }
    }
    

提交回复
热议问题