command_line.go 715 B

1234567891011121314151617181920212223242526
  1. package core
  2. import (
  3. "context"
  4. "errors"
  5. "os/exec"
  6. "time"
  7. )
  8. func Command(name string, arg ...string) (string, error) {
  9. ctxt, cancel := context.WithTimeout(context.Background(), 120*time.Second)
  10. defer cancel() //releases resources if slowOperation completes before timeout elapses
  11. cmd := exec.CommandContext(ctxt, name, arg...)
  12. //当经过Timeout时间后,程序依然没有运行完,则会杀掉进程,ctxt也会有err信息
  13. if out, err := cmd.Output(); err != nil {
  14. //检测报错是否是因为超时引起的
  15. if ctxt.Err() != nil && ctxt.Err() == context.DeadlineExceeded {
  16. return "", errors.New("command timeout")
  17. }
  18. return string(out), err
  19. } else {
  20. return string(out), nil
  21. }
  22. }