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 (

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


Related Posts

  • Assert vs require in testify
  • Handling Unix timestamps in JSON
  • Parsing a key pair from a PEM file in Go
  • Pointer vs value receivers
  • The beauty of io.Reader in Go