Subprocess Timeout Runner

Run a child process under a context deadline, capture stdout and stderr together, and report a clear timeout error.

GoResilience

Code

gosnippet
44 lines
package main

import (
	"bytes"
	"context"
	"errors"
	"flag"
	"fmt"
	"os"
	"os/exec"
	"time"
)

func RunWithTimeout(ctx context.Context, timeout time.Duration, name string, args ...string) (string, error) {
	runCtx, cancel := context.WithTimeout(ctx, timeout)
	defer cancel()

	command := exec.CommandContext(runCtx, name, args...)
	var output bytes.Buffer
	command.Stdout = &output
	command.Stderr = &output
	err := command.Run()

	if errors.Is(runCtx.Err(), context.DeadlineExceeded) {
		return output.String(), fmt.Errorf("%s timed out after %s", name, timeout)
	}
	if err != nil {
		return output.String(), fmt.Errorf("%s failed: %w: %s", name, err, output.String())
	}
	return output.String(), nil
}

func main() {
	child := flag.Bool("child", false, "run as the slow child process")
	flag.Parse()
	if *child {
		time.Sleep(2 * time.Second)
		fmt.Println("child finished")
		return
	}

	output, err := RunWithTimeout(context.Background(), 300*time.Millisecond, os.Args[0], "-child")
	fmt.Printf("output=%q err=%v\n", output, err)
}

What the code does

Subprocess Timeout Runner is built around the functions RunWithTimeout and main.

Every fallible call checks err != nil (1 site), so an error is handled where it happens rather than bubbling invisibly. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.

Watch out for

  • Error values are returned, not thrown — every call site must inspect err before using the other return values.

Using it

Signature: func RunWithTimeout(ctx context.Context, timeout time.Duration, name string, args ...string) (string, error)

The demo output is labeled (child finished, output=), so the printed lines read as a trace of the operations that ran.

main is the driver: it invokes RunWithTimeout before returning.

Key statements

if errors.Is(runCtx.Err(), context.DeadlineExceeded) {
return output.String(), fmt.Errorf("%s timed out after %s", name, timeout)
}
return output.String(), fmt.Errorf("%s failed: %w: %s", name, err, output.String())
func main() {
child := flag.Bool("child", false, "run as the slow child process")
flag.Parse()
if *child {
time.Sleep(2 * time.Second)
fmt.Println("child finished")
return
}
output, err := RunWithTimeout(context.Background(), 300*time.Millisecond, os.Args[0], "-child")
fmt.Printf("output=%q err=%v\n", output, err)
}

Interactive Tools for This Topic

FAQ

How are errors reported?
The Go way: `err` comes back from each call, and 1 checkpoint here test it before proceeding.
What does Subprocess Timeout Runner print when run?
Run it as a complete program — the output lines carry labels such as `child finished`, `output=`.