英文:
Golang: Kill an os.Process with exec.ExitError
问题
如果我有一个名为"myCmd"的os.Exec对象,并且我调用myCmd.Process.Kill(),进程的返回代码行为是什么?它会返回一个exec.ExitError吗?我想强制终止os.Exec进程(即类似于kill -9),让它返回一个exec.ExitError或者其他可以让我的goroutine区分正常命令退出(返回代码为0)的东西。
目前我有以下代码:
myCmd.Start()
var cmdWatcher = func(childCmd os.Cmd) {
err := childCmd.Wait()
if exitErr, k := err.(*exec.ExitError); k {
fmt.Print("检测到ExitError")
}
return
}
go cmdWatcher(myCmd)
myCmd.Process.Kill()
英文:
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()
答案1
得分: 1
Kill()
与在进程上调用kill -9
相同,它发送一个SIGKILL
信号,该信号无法被捕获。与所有非零退出码一样,Wait()
将返回一个ExitError
。
你还可以使用Process.Signal()
选项,它允许你指定任何你想要的信号(例如,SIGINT
或SIGTERM
)。不幸的是,os.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
.
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论