package mainimport (34;context""fmt""os/exec""time")func main() {// 创建超时contextctx, cancel := context.WithTimeout(context.Background(), 3time.Second)defer cancel() // The cancel should be deferred so resources are cleaned up// 拼接命令cmd := exec.CommandContext(ctx, "ping", "-c 100", "-i 1", "114.114.114.114")fmt.Println("2", time.Now())// 获取cmd结果out, err := cmd.Output()// 判断是否超时if ctx.Err() == context.DeadlineExceeded {fmt.Println("Command timed out")return}// 正常返回fmt.Println("Output:", string(out))if err != nil {fmt.Println("Non-zero exit code:", err)}}
如果超时后,实行的命令cmd将会被kill 掉。