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.Command("sleep", "5")
err := cmd.Start()
if err != nil {
log.Fatal(err)
}
log.Printf("Waiting for command to finish...")
err = cmd.Wait()
log.Printf("Command finished with error: %v", err)
Is there a way to terminate that process ahead of time, perhaps after 3 seconds?
Run and terminate an
exec.Process:Run and terminate an
exec.Processafter a timeout:See this example in the Go docs
Legacy
Before Go 1.7, we didn’t have the
contextpackage and this answer was different.Run and terminate an
exec.Processafter a timeout using channels and a goroutine:Either the process ends and its error (if any) is received through
doneor 3 seconds have passed and the program is killed before it’s finished.