2018-07-11 17:27:47 +02:00
|
|
|
package util
|
|
|
|
|
|
|
|
import (
|
2018-12-09 14:56:46 +01:00
|
|
|
"bytes"
|
2018-07-11 17:27:47 +02:00
|
|
|
"context"
|
|
|
|
"os/exec"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Process struct {
|
2018-12-09 14:56:46 +01:00
|
|
|
cmd *exec.Cmd
|
|
|
|
cancel context.CancelFunc
|
|
|
|
errorOutput *bytes.Buffer
|
|
|
|
|
|
|
|
beforeStopHandler func()
|
2018-07-11 17:27:47 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewProcess(path string, params []string) *Process {
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
cmd := exec.CommandContext(ctx, path, params...)
|
2018-12-09 14:56:46 +01:00
|
|
|
p := &Process{
|
2018-07-11 17:27:47 +02:00
|
|
|
cmd: cmd,
|
|
|
|
cancel: cancel,
|
|
|
|
}
|
2018-12-09 14:56:46 +01:00
|
|
|
p.errorOutput = bytes.NewBufferString("")
|
|
|
|
cmd.Stderr = p.errorOutput
|
|
|
|
return p
|
2018-07-11 17:27:47 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (p *Process) Start() error {
|
|
|
|
return p.cmd.Start()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *Process) Stop() error {
|
2018-12-09 14:56:46 +01:00
|
|
|
if p.beforeStopHandler != nil {
|
|
|
|
p.beforeStopHandler()
|
|
|
|
}
|
2018-07-11 17:27:47 +02:00
|
|
|
p.cancel()
|
|
|
|
return p.cmd.Wait()
|
|
|
|
}
|
2018-12-09 14:56:46 +01:00
|
|
|
|
|
|
|
func (p *Process) ErrorOutput() string {
|
|
|
|
return p.errorOutput.String()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *Process) SetBeforeStopHandler(fn func()) {
|
|
|
|
p.beforeStopHandler = fn
|
|
|
|
}
|