2015-02-10 08:56:16 -07:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"os/exec"
|
2015-02-10 13:38:21 -07:00
|
|
|
"log"
|
2015-02-10 08:56:16 -07:00
|
|
|
)
|
|
|
|
|
2015-02-10 13:38:21 -07:00
|
|
|
type ReadWriteCloserWrapper struct {
|
2015-02-10 08:56:16 -07:00
|
|
|
Reader io.ReadCloser
|
|
|
|
Writer io.WriteCloser
|
2015-02-10 13:38:21 -07:00
|
|
|
cmd *exec.Cmd
|
2015-02-10 08:56:16 -07:00
|
|
|
}
|
|
|
|
|
2015-02-10 13:38:21 -07:00
|
|
|
func NewReadWriteCloseWrapper(r io.ReadCloser, w io.WriteCloser) *ReadWriteCloserWrapper {
|
|
|
|
return &ReadWriteCloserWrapper{r, w, nil}
|
2015-02-10 08:56:16 -07:00
|
|
|
}
|
|
|
|
|
2015-02-10 13:38:21 -07:00
|
|
|
func (w *ReadWriteCloserWrapper) Close() (error) {
|
2015-02-10 08:56:16 -07:00
|
|
|
err1 := w.Reader.Close()
|
|
|
|
err2 := w.Writer.Close()
|
2015-02-10 13:38:21 -07:00
|
|
|
if w.cmd != nil{
|
|
|
|
w.cmd.Wait()
|
|
|
|
}
|
2015-02-10 08:56:16 -07:00
|
|
|
|
|
|
|
switch {
|
|
|
|
case err1 != nil:
|
|
|
|
return err1
|
|
|
|
case err2 != nil:
|
|
|
|
return err2
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-02-10 13:38:21 -07:00
|
|
|
func (w *ReadWriteCloserWrapper) Read(p []byte) (n int, err error) {
|
|
|
|
n, err = w.Reader.Read(p)
|
2015-02-10 08:56:16 -07:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-02-10 13:38:21 -07:00
|
|
|
func (w *ReadWriteCloserWrapper) Write(p []byte) (n int, err error) {
|
|
|
|
n, err = w.Writer.Write(p)
|
2015-02-10 08:56:16 -07:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-02-10 13:38:21 -07:00
|
|
|
func StartStdioProcess(name string, args []string) (w *ReadWriteCloserWrapper, err error) {
|
|
|
|
w = new(ReadWriteCloserWrapper)
|
|
|
|
|
2015-02-10 08:56:16 -07:00
|
|
|
cmd := exec.Command(name, args...)
|
|
|
|
|
2015-02-10 13:38:21 -07:00
|
|
|
if cmd == nil {
|
|
|
|
log.Fatalf("Can't run command: %v %v", name, args)
|
|
|
|
}
|
|
|
|
|
|
|
|
w.Reader, err = cmd.StdoutPipe()
|
2015-02-10 08:56:16 -07:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2015-02-10 13:38:21 -07:00
|
|
|
w.Writer, err = cmd.StdinPipe()
|
2015-02-10 08:56:16 -07:00
|
|
|
if err != nil {
|
2015-02-10 13:38:21 -07:00
|
|
|
w.Reader.Close()
|
2015-02-10 08:56:16 -07:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err = cmd.Start(); err != nil {
|
2015-02-10 13:38:21 -07:00
|
|
|
w.Reader.Close()
|
|
|
|
w.Writer.Close()
|
2015-02-10 08:56:16 -07:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2015-02-10 13:38:21 -07:00
|
|
|
w.cmd = cmd
|
2015-02-10 08:56:16 -07:00
|
|
|
|
2015-02-10 13:38:21 -07:00
|
|
|
return
|
2015-02-10 08:56:16 -07:00
|
|
|
}
|