Golang:使用exec.ExitError杀死os.Process

问题描述:

如果我有一个名为"myCmd"的os.Exec对象,并且调用了myCmd.Process.Kill(),则该进程的返回码行为是什么?它会返回exec.ExitError吗?我想强制杀死os.Exec进程(即i.eo kill -9),让它返回exec.ExitError或我的goroutine可以区分出正常的cmd退出(返回代码为0)的东西.

If I have a os.Exec object called "myCmd" and I call myCmd.Process.Kill(), what is the return code behavior of the process? Will it return a exec.ExitError? I want to forcefully kill the os.Exec process (i.eo kill -9), have it return a exec.ExitError or something that my goroutine can distinguish for a normal cmd exit with return code 0.

到目前为止我所拥有的:

What I have so far:

myCmd.Start()

var cmdWatcher = func(childCmd os.Cmd) {

    err := childCmd.Wait()
    if exitErr, k := err.(*exec.ExitError); k {
        fmt.Print("ExitError detected")
    }
    return 
}

go cmdWatcher(myCmd)

myCmd.Process.Kill()

Kill()与在进程上调用 kill -9 相同,它会发送 SIGKILL ,无法捕获.与所有非零退出代码一样, Wait()随后将返回 ExitError .

Kill() is the same as calling kill -9 on the process, it sends a SIGKILL, which cannot be caught. As with all non-zero exit codes, Wait() will then return an ExitError.

您还可以选择使用 Process.Signal(),它允许您指定所需的任何信号(例如, SIGINT SIGTERM ).不幸的是,它看起来不像os.ExitError类型,它允许您以退出状态字符串以外的任何形式检索退出代码本身.但是,您仍然可以使用该错误类型的存在或不存在来指示非零或零退出状态.

You also have the option of using Process.Signal(), which alloww you to specify any signal you want (for example, SIGINT or SIGTERM instead). Unfortunately, it doesn't look like the os.ExitError type allows you to retrieve the exit code itself as anything except the exit status string. However, you can still use the presence or absence of that error type as indication of non-zero or zero exit status.