nezha/cmd/agent/processgroup/process_group.go

55 lines
1.1 KiB
Go
Raw Normal View History

//go:build !windows
2021-01-28 22:59:35 -05:00
// +build !windows
2021-08-18 05:42:26 -04:00
package processgroup
2021-01-28 22:59:35 -05:00
import (
"os/exec"
"sync"
2021-01-28 22:59:35 -05:00
"syscall"
)
type ProcessExitGroup struct {
cmds []*exec.Cmd
}
func NewProcessExitGroup() (ProcessExitGroup, error) {
return ProcessExitGroup{}, nil
}
func (g *ProcessExitGroup) killChildProcess(c *exec.Cmd) error {
pgid, err := syscall.Getpgid(c.Process.Pid)
if err != nil {
// Fall-back on error. Kill the main process only.
c.Process.Kill()
}
// Kill the whole process group.
syscall.Kill(-pgid, syscall.SIGTERM)
return c.Wait()
}
func (g *ProcessExitGroup) Dispose() []error {
var errors []error
mutex := new(sync.Mutex)
wg := new(sync.WaitGroup)
wg.Add(len(g.cmds))
2021-01-28 22:59:35 -05:00
for _, c := range g.cmds {
go func(c *exec.Cmd) {
defer wg.Done()
if err := g.killChildProcess(c); err != nil {
mutex.Lock()
defer mutex.Unlock()
errors = append(errors, err)
}
}(c)
2021-01-28 22:59:35 -05:00
}
wg.Wait()
return errors
2021-01-28 22:59:35 -05:00
}
func (g *ProcessExitGroup) AddProcess(cmd *exec.Cmd) error {
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
g.cmds = append(g.cmds, cmd)
return nil
}