process.go 995 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package process
  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. stdOutput *bytes.Buffer
  12. beforeStopHandler func()
  13. }
  14. func New(path string, params []string) *Process {
  15. ctx, cancel := context.WithCancel(context.Background())
  16. cmd := exec.CommandContext(ctx, path, params...)
  17. p := &Process{
  18. cmd: cmd,
  19. cancel: cancel,
  20. }
  21. p.errorOutput = bytes.NewBufferString("")
  22. p.stdOutput = bytes.NewBufferString("")
  23. cmd.Stderr = p.errorOutput
  24. cmd.Stdout = p.stdOutput
  25. return p
  26. }
  27. func (p *Process) Start() error {
  28. return p.cmd.Start()
  29. }
  30. func (p *Process) Stop() error {
  31. if p.beforeStopHandler != nil {
  32. p.beforeStopHandler()
  33. }
  34. p.cancel()
  35. return p.cmd.Wait()
  36. }
  37. func (p *Process) ErrorOutput() string {
  38. return p.errorOutput.String()
  39. }
  40. func (p *Process) StdOutput() string {
  41. return p.stdOutput.String()
  42. }
  43. func (p *Process) SetBeforeStopHandler(fn func()) {
  44. p.beforeStopHandler = fn
  45. }