英文:
How to kill subprocess on terminating main process in Go language
问题
当主进程终止时,我想要终止子进程。
我使用exec.Command()
来运行子进程。
然而,主进程可能因为意外错误而被终止,所以我想确保子进程也被终止。
在Go语言中如何实现这一点?
英文:
I want to kill subprocesses when main process is terminating.
I am running the subprocess with exec.Command()
However the main process can be terminated by an unexpected error so I want to be sure the subprocess also be terminated too.
How to archive it in Go language?
答案1
得分: 2
你可能想要使用CommandContext
来代替,当主进程被终止时取消上下文。以下是两个示例:第一个示例演示了在短时间超时后终止进程,第二个示例演示了在进程捕获到来自操作系统的外部终止信号时终止子进程:
package main
import (
"context"
"os/exec"
"time"
)
func main() {
// 基于时间持续时间终止命令
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
if err := exec.CommandContext(ctx, "sleep", "5").Run(); err != nil {
// 这将在100毫秒后失败。5秒的休眠将被中断。
}
// 或者使用操作系统信号来取消上下文
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
}
英文:
You might want to use CommandContext
instead, and cancel the context when your main process is being terminated. Below are two examples: the first one is for a simple demonstration of terminating a process after a short timeout, the second is for terminating a sub-process when your process catches external termination signal from the OS:
package main
import (
"context"
"os/exec"
"time"
)
func main() {
// terminate the command based on time.Duration
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
if err := exec.CommandContext(ctx, "sleep", "5").Run(); err != nil {
// This will fail after 100 milliseconds. The 5 second sleep
// will be interrupted.
}
// or use os signals to cancel the context
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论