Standard library / os
os.ProcAttr
Specifies child working directory, environment, inherited files and OS-specific attributes. Files entries 0, 1, 2 correspond to standard streams; nil Env inherits the parent environment. Example intended for Linux/AMD64 with Go 1.23.2 in a disposable working directory; other platforms may differ. Expected stdout: 'true\n'.
Formal Syntax & Structure
go syntaxgo
type ProcAttr struct { Dir string Env []string Files []*File Sys *syscall.SysProcAttr}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 main() { if len(os.Args) > 2 && os.Args[1] == "child" { childMain() return } p, e := os.Executable() must(e) a := &os.ProcAttr{Env: []string{}, Files: []*os.File{nil, os.Stdout, os.Stderr}} c, e := os.StartProcess(p, []string{p, "child", "ok"}, a) must(e) s, e := c.Wait() must(e) fmt.Println(s.Success())}