golang-exec-timeout

golang cmd exec timeout

golang的os/exec包中并没有实现超时方法,但是很多时候会有这样的需求,于是自己写了例子。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package main

import (
"errors"
"fmt"
"os/exec"
"time"
)

type Result struct {
data []byte
err error
}

var ErrorExecTimeout = errors.New("exec timeout")

func Exec(cmd string, timeout int64) ([]byte, error) {
c := exec.Command("/bin/bash", "-c", cmd)
t := time.NewTimer(time.Duration(timeout) * time.Second)
done := make(chan bool)
result := &Result{data: []byte{}, err: nil}
go myExec(c, done, result)
select {
case <-done:
// fmt.Println("exec done")
return result.data, result.err
case <-t.C:
c.Process.Kill()
// fmt.Println("timeout")
result.err = ErrorExecTimeout
return result.data, result.err
}
}

func myExec(c *exec.Cmd, ch chan bool, result *Result) {
result.data, result.err = c.CombinedOutput()
ch <- true
}

func main() {
output, err := Exec("sleep 6&&echo hello", 5)
fmt.Println(string(output), err)
}