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
:
1package main
2
3import (
4 "context"
5 "os/exec"
6)
7
8func main() {
9 ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
10 defer cancel()
11
12 cmd := exec.CommandContext(ctx, "sleep", "5")
13
14 out, err := cmd.CombinedOutput()
15
16 if (ctx.Err() == context.DeadlineExceeded) {
17 // Command was killed
18 }
19
20 if err != nil {
21 // If the command was killed, err will be "signal: killed"
22 // If the command wasn't killed, it contains the actual error, e.g. invalid command
23 }
24}
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.