Standard library / os
os.StartProcess()
Starts a program with explicit argv and process attributes. Unlike exec.Command it does not search PATH. Wait to reap the owned child. Example intended for Linux/AMD64 with Go 1.23.2 in a disposable working directory; other platforms may differ. Expected stdout: '7\n'.
Formal Syntax & Structure
go syntaxgo
func StartProcess(name string, argv []string, attr *ProcAttr) (*Process, error)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| name | string | File or executable name, according to the operation. |
| argv | []string | Child argument vector, including argv[0]. |
| attr | *ProcAttr | Child process attributes. |
Return Value
(*Process, error)
Starts a program with explicit argv and process attributes.
Working Example
Example Snippetgo
package main
import ( "fmt" "io" "os" "os/exec" "time")
func must(e error) { if e != nil { panic(e) }}func child(args ...string) *exec.Cmd { p, e := os.Executable() must(e) c := exec.Command(p, append([]string{"child"}, args...)...) c.Env = []string{} return c}func childMain() { switch os.Args[2] { case "ok": return case "exit7": os.Exit(7) case "sleep": time.Sleep(3 * time.Second) case "arg": fmt.Println(os.Args[3]) case "both": fmt.Fprintln(os.Stdout, "out") fmt.Fprintln(os.Stderr, "err") case "echo": _, e := io.Copy(os.Stdout, os.Stdin) must(e) default: os.Exit(2) }}func start(mode string) (*os.Process, error) { p, e := os.Executable() if e != nil { return nil, e } return os.StartProcess(p, []string{p, "child", mode}, &os.ProcAttr{Env: []string{}, Files: []*os.File{nil, os.Stdout, os.Stderr}})}func main() { if len(os.Args) > 2 && os.Args[1] == "child" { childMain() return } p, e := start("exit7") must(e) s, e := p.Wait() must(e) fmt.Println(s.ExitCode())}