Skip to content

Instantly share code, notes, and snippets.

@viveksyngh
Created August 28, 2018 14:18
Show Gist options
  • Save viveksyngh/df64846d520d86b64453809e2176dbd5 to your computer and use it in GitHub Desktop.
Save viveksyngh/df64846d520d86b64453809e2176dbd5 to your computer and use it in GitHub Desktop.
//CommandTimeoutWithChannel command timeout using channel and goroutine
func CommandTimeoutWithChannel(command string, timeout time.Duration) (string, error) {
cmd := exec.Command("/bin/bash", "-c", command)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Start()
if err != nil {
log.Printf("Error : %s", err.Error())
return err.Error(), err
}
done := make(chan error)
go func() { done <- cmd.Wait() }()
timer := time.After(timeout)
select {
case <-timer:
cmd.Process.Kill()
fmt.Println("Command timed out")
return "Command timed out", errors.New("Command Timeout")
case err := <-done:
if err != nil {
return err.Error(), err
}
return out.String(), nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment