-
Notifications
You must be signed in to change notification settings - Fork 8
/
async.go
77 lines (66 loc) · 1.36 KB
/
async.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
package main
import (
"bufio"
"errors"
"fmt"
"os"
"os/exec"
"time"
)
var check func(string, error) = func(what string, e error) {
if e != nil {
fmt.Println("Error", what+":", e.Error())
os.Exit(1000)
}
}
func main() {
cmd := exec.Command("go", "run", "loop.go")
//cmd := exec.Command("cat")
stdin, err := cmd.StdinPipe()
check("stdin", err)
defer stdin.Close()
stdout, err := cmd.StdoutPipe()
check("stdout", err)
defer stdout.Close()
err = cmd.Start()
check("Start", err)
fmt.Println("Starting")
bufin := bufio.NewWriter(stdin)
bufout := bufio.NewReader(stdout)
for i := 1; i <= 10; i++ {
fmt.Println("Attempt sending data ", i)
SendIn(bufin, fmt.Sprintf("Command-%d", i))
if i == 10 {
SendIn(bufin, "exit")
}
}
for {
out := GetOut(bufout)
if out == "exit" {
break
}
time.Sleep(10 * time.Millisecond)
}
err = cmd.Wait()
check("wait", err)
fmt.Println("Done")
}
func SendIn(bufin *bufio.Writer, data string) {
iwrite, ewrite := bufin.WriteString(data + "\n")
check("write", ewrite)
if iwrite == 0 {
check("write", errors.New("Writing only 0 byte"))
} else {
err := bufin.Flush()
check("Flush", err)
}
}
func GetOut(bufout *bufio.Reader) string {
bread, eread := bufout.ReadString('\n')
if eread != nil && eread.Error() == "EOF" {
return "exit"
}
check("read", eread)
fmt.Println("Read: ", bread)
return bread
}