process.go 834 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package util
  2. import (
  3. "bytes"
  4. "context"
  5. "os/exec"
  6. )
  7. type Process struct {
  8. cmd *exec.Cmd
  9. cancel context.CancelFunc
  10. errorOutput *bytes.Buffer
  11. beforeStopHandler func()
  12. }
  13. func NewProcess(path string, params []string) *Process {
  14. ctx, cancel := context.WithCancel(context.Background())
  15. cmd := exec.CommandContext(ctx, path, params...)
  16. p := &Process{
  17. cmd: cmd,
  18. cancel: cancel,
  19. }
  20. p.errorOutput = bytes.NewBufferString("")
  21. cmd.Stderr = p.errorOutput
  22. return p
  23. }
  24. func (p *Process) Start() error {
  25. return p.cmd.Start()
  26. }
  27. func (p *Process) Stop() error {
  28. if p.beforeStopHandler != nil {
  29. p.beforeStopHandler()
  30. }
  31. p.cancel()
  32. return p.cmd.Wait()
  33. }
  34. func (p *Process) ErrorOutput() string {
  35. return p.errorOutput.String()
  36. }
  37. func (p *Process) SetBeforeStopHandler(fn func()) {
  38. p.beforeStopHandler = fn
  39. }