Skip to content

Instantly share code, notes, and snippets.

@viveksyngh
Created August 28, 2018 14:14
Show Gist options
  • Save viveksyngh/b34c295984a9888d2badcc42f3d7d65c to your computer and use it in GitHub Desktop.
Save viveksyngh/b34c295984a9888d2badcc42f3d7d65c to your computer and use it in GitHub Desktop.
func CommandTimeoutWithTimer(command string, timeout time.Duration) (string, error) {
cmd := exec.Command("/bin/bash", "-c", command)
timer := time.AfterFunc(timeout, func() {
cmd.Process.Kill()
})
out, err := cmd.CombinedOutput()
isExpired := timer.Stop()
if isExpired == false {
fmt.Println("Command timed out")
return "Command timed out", errors.New("Command Timeout")
}
if err != nil {
log.Printf("Error : %s", 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