目前,我正在使用 Golang os.exec.Cmd.Process.Kill() 方法终止一个进程(在 Ubuntu 机器上)。
这似乎会立即终止进程,而不是优雅地终止。我正在启动的一些进程也会写入文件,这会导致文件被截断。
我想用 SIGTERM 而不是使用 Golang 的 SIGKILL 优雅地终止进程。
这是一个使用 cmd.Process.Kill() 启动然后终止的进程的简单示例,我想要在 Golang 中替代使用 SIGTERM 而不是 SIGKILL 的 Kill() 方法,谢谢!
import "os/exec"
cmd := exec.Command("nc", "example.com", "80")
if err := cmd.Start(); err != nil {
log.Print(err)
}
go func() {
cmd.Wait()
}()
// Kill the process - this seems to kill the process ungracefully
cmd.Process.Kill()
最佳答案
您可以使用 Signal() API。支持的Syscalls在这里。
所以基本上你可能想要使用
cmd.Process.Signal(syscall.SIGTERM)
另外请注意按照文档。
The only signal values guaranteed to be present in the os package on all systems are os.Interrupt (send the process an interrupt) and os.Kill (force the process to exit). On Windows, sending os.Interrupt to a process with os.Process.Signal is not implemented; it will return an error instead of sending a signal.
关于linux - 在 Golang 中,如何使用 SIGTERM 而不是 SIGKILL 终止 os.exec.Cmd 进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68494240/