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?
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"
"os/signal"
)
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()
}