我想在主进程终止时终止子进程。
我正在使用 exec.Command() 运行子进程
但是主进程可能会因意外错误而终止,因此我想确保子进程也被终止。
Go语言如何归档?
您可能想使用 commandcontext
代替,并在 main 时取消上下文进程正在终止。下面是两个示例:第一个是在短暂超时后终止进程的简单演示,第二个是当进程捕获来自操作系统的外部终止信号时终止子进程:
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() }