-
Notifications
You must be signed in to change notification settings - Fork 0
/
subprocess.go
86 lines (73 loc) · 1.55 KB
/
subprocess.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
package main
import (
"bufio"
"log"
"os"
"os/exec"
"strings"
)
var proc *subprocess
type subprocess struct {
cmd *exec.Cmd
stdin *os.File
stdout *bufio.Scanner
debug bool
}
func initSubprocess(bin string, broker string) {
stdinChild, stdin, err := os.Pipe()
if err != nil {
log.Fatal("os.Pipe error", err)
}
stdout, stdoutChild, err := os.Pipe()
if err != nil {
log.Fatal("os.Pipe error", err)
}
cmd := exec.Command(bin, broker)
cmd.Stdin = stdinChild
cmd.Stdout = stdoutChild
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
log.Fatal("Command.Start error", err)
}
log.Print("started client subprocess: ", bin)
proc = &subprocess{
cmd: cmd,
stdin: stdin,
stdout: bufio.NewScanner(stdout),
}
}
func (proc *subprocess) writeLine(cmd ...string) {
line := strings.Join(cmd, "\t")
if proc.debug {
log.Print(">> " + line)
}
_, err := proc.stdin.WriteString(line + "\n")
if err != nil {
log.Fatal("subprocess stdin error", err)
}
}
func (proc *subprocess) readLine() []string {
if !proc.stdout.Scan() {
log.Fatal("subprocess stdout error", proc.stdout.Err())
}
line := proc.stdout.Text()
if proc.debug {
log.Print("<< " + line)
}
return strings.Split(line, "\t")
}
func (proc *subprocess) expect(res, descr string) string {
cmd := proc.readLine()
if !assert(cmd[0] == res, descr) {
log.Print(cmd)
return ""
}
return cmd[1]
}
func (proc *subprocess) stop() {
proc.stdin.Close()
if err := proc.cmd.Wait(); err != nil {
log.Fatal("Command.Wait error", err)
}
log.Print("subprocess clean exit")
}