在Go代码中超时杀死进程 [英] Killing processes on timeout in Go code

查看:970
本文介绍了在Go代码中超时杀死进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段时间需要杀死一个进程的情况。我开始这个过程,然后

I have a situations 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆