-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocess.go
121 lines (105 loc) · 2.02 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
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
package usi
import (
"bufio"
"context"
"io"
"log"
"os/exec"
"sync"
"github.com/kk-no/go-usi/usicmd"
)
type ReadWriteProcessor interface {
Start(ctx context.Context)
Stop() error
Write(ctx context.Context)
Read(ctx context.Context)
SendCommand(command usicmd.Command)
}
type process struct {
cmd *exec.Cmd
wg *sync.WaitGroup
cancel context.CancelFunc
procIn io.WriteCloser
procOut io.ReadCloser
sendQueue chan usicmd.Command
}
func NewReadWriteProcessor(ctx context.Context, name string) (ReadWriteProcessor, error) {
p := &process{}
p.wg = &sync.WaitGroup{}
p.cmd = exec.CommandContext(ctx, name)
p.sendQueue = make(chan usicmd.Command)
var err error
if p.procIn, err = p.cmd.StdinPipe(); err != nil {
return nil, err
}
if p.procOut, err = p.cmd.StdoutPipe(); err != nil {
return nil, err
}
if err := p.cmd.Start(); err != nil {
return nil, err
}
return p, nil
}
func (p *process) Start(ctx context.Context) {
ctx, cancel := context.WithCancel(ctx)
p.cancel = cancel
p.wg.Add(1)
go p.Read(ctx)
p.wg.Add(1)
go p.Write(ctx)
}
func (p *process) Stop() error {
if p.cancel != nil {
p.cancel()
p.wg.Wait()
}
if p.sendQueue != nil {
close(p.sendQueue)
}
if p.procIn != nil {
if err := p.procIn.Close(); err != nil {
return err
}
}
if p.procOut != nil {
if err := p.procOut.Close(); err != nil {
return err
}
}
return nil
}
func (p *process) Write(ctx context.Context) {
for {
select {
case <-ctx.Done():
p.wg.Done()
return
default:
command := <-p.sendQueue
log.Println(">", command)
if _, err := p.procIn.Write([]byte(command + "\n")); err != nil {
return
}
}
}
}
func (p *process) Read(ctx context.Context) {
scanner := bufio.NewScanner(p.procOut)
for {
select {
case <-ctx.Done():
p.wg.Done()
return
default:
if scanner.Scan() {
log.Println("<", scanner.Text())
}
if err := scanner.Err(); err != nil {
return
}
}
}
}
func (p *process) SendCommand(command usicmd.Command) {
p.sendQueue <- command
}