实现要点
os.Pipe 返回两个 *os.File 描述符——r 读端、w 写端。goroutine 向 w 写入两行后关闭它;正是关闭动作让读端收到 EOF,Scanner 循环才能结束而不是永远阻塞。
读端把两行收齐并拼接打印,随后打印 r 的类型 *os.File——这正是与 io.Pipe 的差别:内核级描述符可以传给子进程,io.Pipe 只是内存抽象。
细节提醒
- 两端都要关闭;r.Close() 在 Scan 循环结束后执行。
- Scanner 按行缓冲,与 Fprintln 的逐行写入一一对应。
核心语句
r, w, err := os.Pipe()
w.Close()
代码示例
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))
}