forked from nanjishidu/gomini
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd.go
55 lines (52 loc) · 1021 Bytes
/
cmd.go
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
44
45
46
47
48
49
50
51
52
53
54
55
package gomini
import (
"bytes"
"errors"
"os/exec"
"time"
)
func Exec(bin string, args ...string) (string, error) {
cmd := exec.Command(bin, args...)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
return "", err
}
return out.String(), nil
}
func ExecWithTimeout(bin string, timeout time.Duration, args ...string) (string, error) {
cmd := exec.Command(bin, args...)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Start()
if err != nil {
return "", err
}
err, isTimeout := CmdRunWithTimeout(cmd, timeout)
if err != nil {
return "", err
}
if isTimeout {
return "", errors.New("cmd run timeout")
}
return out.String(), nil
}
func CmdRunWithTimeout(cmd *exec.Cmd, timeout time.Duration) (error, bool) {
done := make(chan error)
go func() {
done <- cmd.Wait()
}()
var err error
select {
case <-time.After(timeout):
<-done
err = cmd.Process.Kill()
if err != nil {
return err, true
}
return nil, true
case err = <-done:
return err, false
}
}