Download this file
| 1 | //go:build unix |
| 2 | |
| 3 | package thin |
| 4 | |
| 5 | import ( |
| 6 | "errors" |
| 7 | "os/exec" |
| 8 | "syscall" |
| 9 | ) |
| 10 | |
| 11 | // ownGroup starts cmd in a process group of its own and makes the end of |
| 12 | // its context kill that whole group, not only cmd: a grandchild that |
| 13 | // ignores SIGTERM and holds cmd's output dies with it. |
| 14 | func ownGroup(cmd *exec.Cmd) { |
| 15 | cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} |
| 16 | cmd.Cancel = func() error { return killGroup(cmd) } |
| 17 | } |
| 18 | |
| 19 | // killGroup sends SIGKILL to cmd's process group (-pgid); a group that |
| 20 | // is already gone is not an error. |
| 21 | func killGroup(cmd *exec.Cmd) error { |
| 22 | if cmd.Process == nil { |
| 23 | return nil |
| 24 | } |
| 25 | if err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL); err != nil && !errors.Is(err, syscall.ESRCH) { |
| 26 | return err |
| 27 | } |
| 28 | return nil |
| 29 | } |
| 30 | |