Is there a way to terminate a process started with os.exec in Golang? For example (from http://golang.org/pkg/os/exec/#example_Cmd_Start),
cmd := exec.Comma
The other answers are right about calling Kill(), but the parts regarding killing the process after a timeout are little outdated now.
This can be done now with the context package and exec.CommandContext (example adapted from the example in the docs):
func main() {
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.
}
}
From the docs:
The provided context is used to kill the process (by calling os.Process.Kill) if the context becomes done before the command completes on its own.
After the Run() completes, you can inspect ctx.Err(). If the timeout was reached, the type of the error returned will be DeadLineExceeded. If it's nil, check the err returned by Run() to see if the command completed without errors.