Subprocess Pipes Stream Stdin And Stdout

Pipe data through a subprocess with StdinPipe and StdoutPipe: write lines to the child, stream its sorted output back with a Scanner, then Wait for exit.

GoCli Tooling

Code

gosnippet
43 lines
package main

import (
	"bufio"
	"fmt"
	"os/exec"
	"strings"
)

func main() {
	// subprocess pipes: write stdin, stream stdout back
	cmd := exec.Command("sort")
	stdin, err := cmd.StdinPipe()
	if err != nil {
		panic(err)
	}
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		panic(err)
	}
	if err := cmd.Start(); err != nil {
		panic(err)
	}

	// writer side: close right after writing so the child reads EOF
	go func() {
		for _, line := range []string{"banana", "apple", "cherry"} {
			fmt.Fprintln(stdin, line)
		}
		stdin.Close()
	}()

	// reader side: the Scanner streams the child output as sorting completes
	sc := bufio.NewScanner(stdout)
	var got []string
	for sc.Scan() {
		got = append(got, sc.Text())
	}
	if err := cmd.Wait(); err != nil {
		panic(err)
	}
	fmt.Println("sorted:", strings.Join(got, ","))
}

What the demo wires

exec.Command(“sort”) gets a StdinPipe and a StdoutPipe, then Start launches the child. A goroutine writes banana, apple and cherry into the stdin pipe and closes it immediately; that close is the EOF the sort program waits for.

On the read side, a Scanner drains the stdout pipe line by line as sorting completes, collecting the three words in sorted order. cmd.Wait reaps the process after the pipes are done, and the joined output prints sorted: apple,banana,cherry.

Caveats and details

  • StdoutPipe must be fully read before Wait, which the Scan loop guarantees.
  • Not closing stdin would leave sort blocked on its input forever.

Interactive Tools for This Topic

FAQ

Why close the stdin pipe before reading stdout?
sort processes its whole input only after EOF; closing the write end lets the child finish and flush, which is what the Scanner then streams back line by line.