Skip to content

Instantly share code, notes, and snippets.

@viveksyngh
Created August 28, 2018 14:20
Show Gist options
  • Save viveksyngh/98287c04adc0d0536b56273bccad97cf to your computer and use it in GitHub Desktop.
Save viveksyngh/98287c04adc0d0536b56273bccad97cf to your computer and use it in GitHub Desktop.
//CommandTimeoutWithContext command timeout with background context
func CommandTimeoutWithContext(command string, timeout time.Duration) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
cmd := exec.CommandContext(ctx, "/bin/bash", "-c", command)
out, err := cmd.CombinedOutput()
if ctx.Err() == context.DeadlineExceeded {
fmt.Println("Command timed out")
return "Command timed out", errors.New("Command Timeout")
}
if err != nil {
fmt.Println("Error : ", err.Error())
return string(out), err
}
return string(out), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment