Pipe and Unix Socket Echo

Two forms of local IPC in one program: an in-kernel os.Pipe, then a Unix domain socket echo server and client addressed by a filesystem path.

package main

import (
	"bufio"
	"fmt"
	"io"
	"net"
	"os"
	"path/filepath"
)

func main() {
	// os.Pipe: a one-way in-kernel byte channel between goroutines or processes.
	r, w, _ := os.Pipe()
	go func() {
		fmt.Fprintln(w, "through the pipe")
		w.Close()
	}()
	line, _ := bufio.NewReader(r).ReadString('\n')
	fmt.Print("pipe says: ", line) // pipe says: through the pipe

	// Unix domain socket: local IPC named by a path on disk.
	sock := filepath.Join(os.TempDir(), "echo.sock")
	os.Remove(sock) // clear any stale socket file from a previous run
	ln, err := net.Listen("unix", sock)
	if err != nil {
		fmt.Println("listen:", err)
		return
	}
	defer ln.Close()
	defer os.Remove(sock)

	// Server: echo everything back.
	go func() {
		conn, err := ln.Accept()
		if err != nil {
			return
		}
		defer conn.Close()
		io.Copy(conn, conn)
	}()

	// Client: send a line, read the echo.
	c, _ := net.Dial("unix", sock)
	defer c.Close()
	fmt.Fprintln(c, "hello over unix socket")
	reply, _ := bufio.NewReader(c).ReadString('\n')
	fmt.Print("socket echo: ", reply) // socket echo: hello over unix socket
}

Save the code as main.go and run it:

go run main.go

Expected output:

pipe says: through the pipe
socket echo: hello over unix socket

💻 Run locally

Copy the code above and run it on your machine

© 2026 ByteLearn.dev. Free courses for developers. · Privacy