We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Sometimes, you need to run a command and kill if it runs too long.
The best approach I've found for doing this is to use a context
with a timeout combined with exec.CommandContext
:
package main
import (
"context"
"os/exec"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "sleep", "5")
out, err := cmd.CombinedOutput()
if (ctx.Err() == context.DeadlineExceeded) {
// Command was killed
}
if err != nil {
// If the command was killed, err will be "signal: killed"
// If the command wasn't killed, it contains the actual error, e.g. invalid command
}
}
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.