command_line.go 760 B

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