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
A simpler version without select and channels.
func main() {
cmd := exec.Command("cat", "/dev/urandom")
cmd.Start()
timer := time.AfterFunc(1*time.Second, func() {
err := cmd.Process.Kill()
if err != nil {
panic(err) // panic as can't kill a process.
}
})
err := cmd.Wait()
timer.Stop()
// read error from here, you will notice the kill from the
fmt.Println(err)
}
Well, after consulting some experienced go programmer, this is apparently not a GOly enough way to solve the problem. So please refer to the accepted answer.
Here is an even shorter version, and very straight forward. BUT, possibly having tons of hanging goroutines if timeout is long.
func main() {
cmd := exec.Command("cat", "/dev/urandom")
cmd.Start()
go func(){
time.Sleep(timeout)
cmd.Process.Kill()
}()
return cmd.Wait()
}