...
1
2
3
4
5
6
7
8
9
10
11
12
13
14 package timer
15
16 import (
17 "bufio"
18 "fmt"
19 "io"
20 "os/exec"
21 "strconv"
22 "strings"
23 "time"
24 )
25
26
27 type Timer struct {
28 Stdin io.WriteCloser
29 TimeChan chan TimeResult
30 process *exec.Cmd
31 pid int
32 }
33
34
35 func (timer *Timer) Pid() int {
36 return timer.pid
37 }
38
39
40 type TimeResult struct {
41 Time *time.Time
42 Error error
43 }
44
45
46 func StartTimer() (*Timer, error) {
47 process := exec.Command("./bin/test/timer")
48
49 stdout, err := process.StdoutPipe()
50 if err != nil {
51 return nil, err
52 }
53 stdoutScanner := bufio.NewScanner(stdout)
54
55 output := make(chan TimeResult)
56 go func() {
57 for stdoutScanner.Scan() {
58 line := stdoutScanner.Text()
59 sections := strings.Split(line, " ")
60
61 sec, err := strconv.ParseInt(sections[0], 10, 64)
62 if err != nil {
63 output <- TimeResult{
64 Error: err,
65 }
66 }
67 nsec, err := strconv.ParseInt(sections[1], 10, 64)
68 if err != nil {
69 output <- TimeResult{
70 Error: err,
71 }
72 }
73
74 t := time.Unix(sec, nsec)
75 output <- TimeResult{
76 Time: &t,
77 }
78 }
79 if err := stdoutScanner.Err(); err != nil {
80 output <- TimeResult{
81 Error: err,
82 }
83 }
84 }()
85
86 stdin, err := process.StdinPipe()
87 if err != nil {
88 return nil, err
89 }
90
91 err = process.Start()
92 if err != nil {
93 return nil, err
94 }
95
96 return &Timer{
97 Stdin: stdin,
98 TimeChan: output,
99 pid: process.Process.Pid,
100 process: process,
101 }, nil
102 }
103
104
105 func (timer *Timer) GetTime() (*time.Time, error) {
106 _, err := fmt.Fprintf(timer.Stdin, "\n")
107 if err != nil {
108 return nil, err
109 }
110
111 result := <-timer.TimeChan
112 if result.Error != nil {
113 return nil, result.Error
114 }
115
116 return result.Time, nil
117 }
118
119
120 func (timer *Timer) Stop() error {
121 _, err := fmt.Fprintf(timer.Stdin, "STOP\n")
122
123 return err
124 }
125