在 Golang 中,如何使用 SIGTERM 而不是 SIGKILL 终止 os.exec.Cmd 进程?

Evy*_*ias 3 linux ubuntu operating-system process go

目前,我正在使用 Golang os.exec.Cmd.Process.Kill()方法(在 Ubuntu 机器上)终止进程。

这似乎是立即终止进程而不是优雅地终止进程。我启动的一些进程也会写入文件,这会导致文件被截断。

我想使用 Golang 使用SIGTERM而不是SIGKILL优雅地终止进程。

这是一个使用 cmd.Process.Kill() 启动然后终止的进程的简单示例,我想要 Golang 中的 Kill() 方法的替代方法,该方法使用 SIGTERM 而不是 SIGKILL,谢谢!

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()
Run Code Online (Sandbox Code Playgroud)

Sha*_*shi 7

您可以使用Signal() API。支持的系统调用在这里。

所以基本上你可能想使用

cmd.Process.Signal(syscall.SIGTERM)
Run Code Online (Sandbox Code Playgroud)

另请按照文档说明。

所有系统上 os 包中保证出现的唯一信号值是 os.Interrupt(向进程发送中断)和 os.Kill(强制进程退出)。在 Windows 上,未实现使用 os.Process.Signal 向进程发送 os.Interrupt;它将返回错误而不是发送信号。