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

标签 linux go ubuntu process operating-system

目前,我正在使用 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/

相关文章:

linux - bash 合并开始和结束相同的行

go - 为什么接口(interface)分配比方法调用更严格?

mongodb - 在 Ubuntu Snap 安装上更改默认 MongoDB 端口

go - 如何将 golang 1.7 上下文与 http.Request(用于身份验证)一起使用

google-app-engine - GO中GAE通过int Id获取实体

php - 连接到/var/www 之外的 SQLite 数据库

linux - Praat 脚本在 Ubuntu 中抛出 "unknown function"错误

c++ - 在 Visual Studio Code 中运行代码时遇到问题

Linux CAN总线传输超时

linux - 是否有任何基于 Linux 的 Excel 文件差异工具?