frp/tests/util/process.go

48 lines
834 B
Go
Raw Normal View History

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