Created
September 24, 2016 22:29
-
-
Save vcabbage/89e22c573e5c031104bc22f4aef8723c to your computer and use it in GitHub Desktop.
Command timeout with context
This file contains 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
package main | |
import ( | |
"context" | |
"fmt" | |
"os/exec" | |
"time" | |
) | |
func main() { | |
// Create a new context and add a timeout to it | |
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) | |
defer cancel() // The cancel should be deferred so resources are cleaned up | |
// Create the command with our context | |
cmd := exec.CommandContext(ctx, "ping", "-c 4", "-i 1", "8.8.8.8") | |
// This time we can simply use Output() to get the result. | |
out, err := cmd.Output() | |
// We want to check the context error to see if the timeout was executed. | |
// The error returned by cmd.Output() will be OS specific based on what | |
// happens when a process is killed. | |
if ctx.Err() == context.DeadlineExceeded { | |
fmt.Println("Command timed out") | |
return | |
} | |
// If there's no context error, we know the command completed (or errored). | |
fmt.Println("Output:", string(out)) | |
if err != nil { | |
fmt.Println("Non-zero exit code:", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment