Spawning Processes
Use os/exec with separate arguments to start processes without a shell; add context cancellation and validate target arguments.
The os/exec package starts external programs without invoking a shell. Pass the executable and each argument separately; shell metacharacters then have no special meaning.
CommandContext runs a program with a context. Output waits for completion and returns captured standard output.
package main
import (
"context"
"fmt"
"os/exec"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
output, err := exec.CommandContext(ctx, "go", "version").Output()
if err != nil {
panic(err)
}
fmt.Print(string(output))
}In production
Use a timeout or cancellation context for processes that may hang. Passing user input as an argument avoids shell injection, but the target program may still interpret that argument as an option or path, so validate it for that program. Check command errors because a non-zero process exit is returned as an error.
Enjoyed this? Get more software craft delivered to your inbox.