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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.