cmd.Wait()"os/exec"// Start the subprocess
cmd := exec.Command("sleep", "500")
err := cmd.Start()
if err != nil {
log.Fatal(err)
}
// Wait for it to finish
done := make(chan struct{})
go (func () {
cmd.Wait()
close(done)
})()
// Set a timeout
timeout := time.NewTimer(5 * time.Second)
select {
case <-done:
fmt.Println("process completed")
if !timeout.Stop() {
<-timeout.C
}
case <-timeout.C:
fmt.Println("deadline ran out, killing process")
if err := cmd.Process.Kill(); err != nil {
log.Fatal("failed to kill process: ", err)
}
<-done
}
只有意志的一个分支select会触发,并且每个分支都会为另一个执行必要的清理工作。在超时情况下,进程被杀死后,Wait()应该立即返回,这应该向“完成”通道发出信号。