-
Notifications
You must be signed in to change notification settings - Fork 1
/
process.go
76 lines (70 loc) · 1.6 KB
/
process.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
65
66
67
68
69
70
71
72
73
74
75
76
package main
import (
"fmt"
"log"
"os/exec"
"syscall"
"time"
"github.com/buildkite/shellwords"
"github.com/go-cmd/cmd"
)
type Process struct {
Id int64 `json:"id"`
Name string `json:"name"`
CreateTime int64 `json:"create_time"`
Command string `json:"command"`
Status int64 `json:"status"`
OrderId int64 `json:"order_id"`
RunStatus string `json:"run_status"`
GoCmd *cmd.Cmd `json:"-"`
StatusChan <-chan cmd.Status `json:"-"`
}
func (p *Process) Run(logsFun func(time int64, t string, l string)) {
c, err := shellwords.Split(p.Command)
if err != nil {
fmt.Println(err)
logsFun(time.Now().UnixMilli(), "err", err.Error())
return
}
fmt.Println(c)
p.GoCmd = cmd.NewCmdOptions(cmd.Options{
Buffered: false,
Streaming: true,
BeforeExec: []func(cmd *exec.Cmd){
func(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: 0x08000000} // CREATE_NO_WINDOW
},
},
}, c[0], c[1:]...)
p.StatusChan = p.GoCmd.Start()
go func() {
for p.GoCmd.Stdout != nil || p.GoCmd.Stderr != nil {
select {
case line, open := <-p.GoCmd.Stdout:
if !open {
p.GoCmd.Stdout = nil
continue
}
logsFun(time.Now().UnixMilli(), "out", line)
case line, open := <-p.GoCmd.Stderr:
if !open {
p.GoCmd.Stderr = nil
continue
}
logsFun(time.Now().UnixMilli(), "err", line)
}
}
}()
}
func (p *Process) Stop() {
if p.GoCmd != nil {
err := p.GoCmd.Stop()
if err != nil {
log.Println(err)
err := KillProcessByPID(p.GoCmd.Status().PID)
if err != nil {
log.Println(err)
}
}
}
}