您如何在Go代码超时时杀死一个进程及其子进程? [英] How do you kill a process and its children on a timeout in Go code?
本文介绍了您如何在Go代码超时时杀死一个进程及其子进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到的情况是一段时间后需要终止进程.我开始该过程,然后:
I have a situation where I need to kill a process after some time. I start the process and then:
case <-time.After(timeout):
if err := cmd.Process.Kill(); err != nil {
return 0, fmt.Errorf("Failed to kill process: %v", err)
}
杀死该过程.但这只会杀死父进程,而不会杀死主进程启动的5-10个子进程.我还尝试创建一个流程组,然后执行以下操作:
kills the process. But it only kills the parent process not the 5-10 child processes that main process starts. I also tried creating a process group and then doing:
syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
杀死主进程和孙进程,但不起作用.还有什么其他方法可以杀死进程.
to kill main and grandchild processes, but not working. Is there any other way I can kill the processes.
推荐答案
我认为这是您需要的:
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")
}
这篇关于您如何在Go代码超时时杀死一个进程及其子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文