/
system.go
64 lines (48 loc) · 1.14 KB
/
system.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
64
package main
import (
"bytes"
"fmt"
"os/exec"
"syscall"
)
func exec_without_output(cmd string, args []string) (bool, error) {
if err := exec.Command(cmd, args...).Run(); err != nil {
return false, err
}
return true, nil
}
func ExecBash(command string, args []string) (int, string, error) {
cmd := exec.Command(command, args...)
var waitStatus syscall.WaitStatus
//Stdout buffer
cmdOutput := &bytes.Buffer{}
//Attach buffer to command stdout
cmd.Stdout = cmdOutput
//Execute command
err := cmd.Run()
defer func() {
if r := recover(); r != nil {
fmt.Printf("Command:%s execute error\n", command)
}
}()
if err != nil {
if exitError, ok := err.(*exec.ExitError); ok {
waitStatus = exitError.Sys().(syscall.WaitStatus)
return waitStatus.ExitStatus(), "", err
} else {
fmt.Println("something wrong")
}
}
waitStatus = cmd.ProcessState.Sys().(syscall.WaitStatus)
return waitStatus.ExitStatus(), cmdOutput.String(), nil
}
func main() {
cmd := "cat"
args := []string{"/home/work/go/AUTHORS"}
a, b := exec_without_output(cmd, args)
if a {
fmt.Println("ok")
} else if b != nil {
fmt.Println(b)
}
}