goexec执行命令,设置超时
我们在使用go执行命令的时候,需要设置超时时间,避免一直卡死。go里面超时最常用的就是context。下面通过一个context的例子演示一下,如何使用context完成 exec超时设置。package main import ( "context" "fmt" "os/exec" "time" ) func main() { // 创建超时context ctx, cancel := context.WithTimeout(context.Background(), 3*time.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 掉。