|
1 | 1 | package sc
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "bufio" |
4 | 5 | "errors"
|
5 | 6 | "fmt"
|
| 7 | + "io" |
6 | 8 | "os"
|
7 | 9 | "os/exec"
|
8 | 10 | "strconv"
|
@@ -89,26 +91,51 @@ func (s *Server) args() ([]string, error) {
|
89 | 91 | return args, nil
|
90 | 92 | }
|
91 | 93 |
|
| 94 | +const ServerReadyMessage = "server ready" |
| 95 | + |
92 | 96 | // Start starts a new instance of scsynth.
|
93 |
| -func (s *Server) Start() error { |
| 97 | +// If the server doesn't print a line containing ServerReadyMessage |
| 98 | +// within the timeout then ErrTimeout is returned. |
| 99 | +func (s *Server) Start(timeout time.Duration) (io.ReadCloser, io.ReadCloser, error) { |
94 | 100 | args, err := s.args()
|
95 | 101 | if err != nil {
|
96 |
| - return err |
| 102 | + return nil, nil, err |
97 | 103 | }
|
98 | 104 |
|
99 | 105 | serverPath, err := s.getServerPath()
|
100 | 106 | if err != nil {
|
101 |
| - return err |
| 107 | + return nil, nil, err |
102 | 108 | }
|
103 | 109 |
|
104 | 110 | s.Cmd = exec.Command(serverPath, args...)
|
| 111 | + stdout, err := s.StdoutPipe() |
| 112 | + if err != nil { |
| 113 | + return nil, nil, err |
| 114 | + } |
| 115 | + stderr, err := s.StderrPipe() |
| 116 | + if err != nil { |
| 117 | + return nil, nil, err |
| 118 | + } |
105 | 119 | if err := s.Cmd.Start(); err != nil {
|
106 |
| - return err |
| 120 | + return nil, nil, err |
107 | 121 | }
|
108 | 122 |
|
109 |
| - // Wait until the server returns a status. |
110 |
| - _, err = NewClient(s.Network, "0.0.0.0:0", fmt.Sprintf("0.0.0.0:%d", s.Port), 5*time.Second) |
111 |
| - return err |
| 123 | + // Wait until the server prints a ready message. |
| 124 | + var ( |
| 125 | + scanner = bufio.NewScanner(stdout) |
| 126 | + start = time.Now() |
| 127 | + ) |
| 128 | + for i := 0; scanner.Scan(); i++ { |
| 129 | + if time.Now().Sub(start) > timeout { |
| 130 | + return nil, nil, ErrTimeout |
| 131 | + } |
| 132 | + if strings.Index(scanner.Text(), ServerReadyMessage) == -1 { |
| 133 | + continue |
| 134 | + } else { |
| 135 | + break |
| 136 | + } |
| 137 | + } |
| 138 | + return stdout, stderr, scanner.Err() |
112 | 139 | }
|
113 | 140 |
|
114 | 141 | // Stop stops a running server.
|
|
0 commit comments