os.Pipe Hands Off File Descriptors

os.Pipe creates a kernel-level pipe of *os.File descriptors: a writer goroutine closes the write end so the Scanner reader reaches EOF cleanly.

GoData Integrity

Code

gosnippet
35 lines
package main

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

func main() {
	// os.Pipe hands off two file descriptors: r to read, w to write
	r, w, err := os.Pipe()
	if err != nil {
		panic(err)
	}

	// close the write end once done so the reader sees EOF
	go func() {
		for _, line := range []string{"alpha", "beta"} {
			fmt.Fprintln(w, line)
		}
		w.Close()
	}()

	sc := bufio.NewScanner(r)
	var lines []string
	for sc.Scan() {
		lines = append(lines, sc.Text())
	}
	r.Close()
	fmt.Println("piped:", strings.Join(lines, ","))

	// unlike io.Pipe: os.Pipe wraps real file descriptors, which can be handed to a subprocess
	fmt.Println("read end type:", fmt.Sprintf("%T", r))
}

What the demo connects

os.Pipe returns two *os.File descriptors, r for reading and w for writing. A goroutine writes two lines into w and closes it; closing is what produces EOF on the read side, so the Scanner loop terminates instead of blocking forever.

The reader accumulates both lines and prints them joined, then the demo prints the type of r, *os.File — the difference from io.Pipe: kernel-backed descriptors can be handed to child processes, while io.Pipe is an in-memory abstraction.

Caveats and details

  • Both ends must be closed; r.Close() runs after the Scan loop finishes.
  • Scanner buffers by line, matching the Fprintln writes one-to-one.

Interactive Tools for This Topic

FAQ

Why does the read side reach EOF?
Because the goroutine closes w after writing both lines; an open write end would leave the Scanner waiting for more data indefinitely instead of finishing the Scan loop.