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 another program without asking a shell, the command-line interpreter, to process the command. Pass the program name and each argument separately so characters such as ; are treated as ordinary text.
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 context stop signal for programs that may never finish. Passing input as an argument avoids letting it run extra shell commands, but the program may still treat that input as an option or path, so check what values it accepts. Check the returned error because a non-zero exit status means the program reported failure.