-
Notifications
You must be signed in to change notification settings - Fork 21
/
cmd.go
63 lines (52 loc) · 1.2 KB
/
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
56
57
58
59
60
61
62
63
package sys
import (
"bytes"
"log"
"os/exec"
"strings"
"syscall"
"time"
)
func CmdOut(name string, arg ...string) (string, error) {
cmd := exec.Command(name, arg...)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
return out.String(), err
}
func CmdOutBytes(name string, arg ...string) ([]byte, error) {
cmd := exec.Command(name, arg...)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
return out.Bytes(), err
}
func CmdOutNoLn(name string, arg ...string) (out string, err error) {
out, err = CmdOut(name, arg...)
if err != nil {
return
}
return strings.TrimSpace(string(out)), nil
}
func CmdRunWithTimeout(cmd *exec.Cmd, timeout time.Duration) (error, bool) {
var err error
done := make(chan error)
go func() {
done <- cmd.Wait()
}()
select {
case <-time.After(timeout):
log.Printf("timeout, process:%s will be killed", cmd.Path)
go func() {
<-done // allow goroutine to exit
}()
//IMPORTANT: cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} is necessary before cmd.Start()
err = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
if err != nil {
log.Println("kill failed, error:", err)
}
return err, true
case err = <-done:
return err, false
}
}