golang执行外部命令超时处理
不至于当前程序挂起,超时杀死超时进程。
doneChan := make(chan bool, 1) errorChan := make(chan error, 1) var cmd *exec.Cmd = exec.Command(name, newArg...) go func () { output, err := cmd.CombinedOutput() if err != nil { log.Printf("execute command failed, output: %s, error: %v\n", string(output), err) errorChan <- err return } doneChan <- true }() select { case <-time.After(30 * time.Second): log.Printf("execute command timeout\n") cmd.Process.Kill() case <-doneChan: // command success case err := <-errorChan: log.Printf("execute command failure, error: %v\n", err) return err }