-
Notifications
You must be signed in to change notification settings - Fork 2
/
worker.go
140 lines (114 loc) · 2.05 KB
/
worker.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package pagent
import (
"errors"
"io"
"os"
"os/exec"
"strings"
"sync"
"time"
"syscall"
)
type _RUNFUNC func(id, info string) error
type _FINFUNC func(id string, err error) error
type Worker struct {
//私有成员
_in io.WriteCloser
_out io.Reader
_pid int
_cmd *exec.Cmd
_master *Master
Running bool
Cond *sync.Cond
//业务。。。
Id string
RunningCall _RUNFUNC
FinishCall _FINFUNC
}
func NewWorker(id string) *Worker {
return &Worker{
Id: id,
Cond: sync.NewCond(&sync.Mutex{}),
}
}
func (r *Worker) Start(cmd string, RunningCall _RUNFUNC, FinishCall _FINFUNC, arg ...string) error {
r._cmd = exec.Command(cmd, arg...)
var err error
if r._in, err = r._cmd.StdinPipe(); err != nil {
return err
}
if r._out, err = r._cmd.StdoutPipe(); err != nil {
return err
}
if err := r._cmd.Start(); err != nil {
return err
}
r.RunningCall = RunningCall
r.FinishCall = FinishCall
r._pid = r._cmd.Process.Pid
if r._master != nil {
r._master.RunWorker(r.Id)
}
return nil
}
func (r *Worker) RegMaster(m *Master) error {
if m == nil {
return errors.New("master == nil")
}
r._master = m
return nil
}
func (r *Worker) Wait() error {
if r._pid == 0 {
return errors.New("r._pid == 0")
}
defer r._in.Close()
err := r._cmd.Wait()
if err != nil {
return err
}
return nil
}
func (r *Worker) Stop() error {
if r._pid == 0 {
return errors.New("r._pid == 0")
}
pro, err := os.FindProcess(r._pid)
if err != nil {
return err
}
err = pro.Signal(syscall.SIGINT)
if err != nil {
return err
}
return nil
}
func (r *Worker) Input(in string) error {
if r._in == nil {
return errors.New("_in == nil")
}
if !strings.Contains(in, "\n") {
in += "\n"
}
i := 0
total := 0
for {
if n, err := r._in.Write([]byte(in)); err != nil {
return err
} else {
total += n
}
if total >= len(in) {
return nil
}
i++
if i > 3 {
return errors.New("write data not enough!")
}
time.Sleep(time.Millisecond * 100)
}
return nil
}
func (r *Worker) Output() io.Reader {
return r._out
}