Created
August 28, 2018 14:20
-
-
Save viveksyngh/98287c04adc0d0536b56273bccad97cf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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