Standard library / os/exec
os/exec.Cmd.StdinPipe()
Returns a writer connected to child stdin. Close to deliver EOF when child needs it, then wait. Example intended for Linux/AMD64 with Go 1.23.2 in a disposable working directory; other platforms may differ. Expected stdout: 'hello\n'.
Formal Syntax & Structure
go syntaxgo
func (c *Cmd) StdinPipe() (io.WriteCloser, error)Return Value
(io.WriteCloser, error)
Returns a writer connected to child stdin.
Working Example
Example Snippetgo
package main
import ( "bytes" "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 } c := child("echo") var b bytes.Buffer c.Stdout = &b w, e := c.StdinPipe() must(e) must(c.Start()) _, e = io.WriteString(w, "hello\n") must(e) must(w.Close()) must(c.Wait()) fmt.Print(b.String())}