我有一种情况,我需要在一段时间后终止一个进程。我开始这个过程,然后:
case <-time.After(timeout):
if err := cmd.Process.Kill(); err != nil {
return 0, fmt.Errorf("Failed to kill process: %v", err)
}
Run Code Online (Sandbox Code Playgroud)
杀死进程。但它只会杀死父进程,而不是主进程启动的 5-10 个子进程。我还尝试创建一个进程组,然后执行以下操作:
syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
Run Code Online (Sandbox Code Playgroud)
杀死主进程和孙进程,但不起作用。有没有其他方法可以杀死进程。
我认为这就是你所需要的:
cmd := exec.Command(command, arguments...)
// This sets up a process group which we kill later.
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if err := cmd.Start(); err != nil {
return err
}
// buffered chan is important so the goroutine does't
// get blocked and stick around if the function returns
// after the timeout
done := make(chan error, 1)
go func() {
done <- cmd.Wait()
}()
select {
case err := <-done:
// this will be nil if no error
return err
case <-time.After(time.Second):
// We created a process group above which we kill here.
pgid, err := syscall.Getpgid(cmd.Process.Pid)
if err != nil {
return err
}
// note the minus sign
if err := syscall.Kill(-pgid, 15); err != nil {
return err
}
return fmt.Errorf("Timeout")
}
Run Code Online (Sandbox Code Playgroud)