Where Go Output Goes: File Descriptors, Redirection, and Sockets
A practical guide to stdout, shell redirection, sockets, and process-local file descriptors.
Why does fmt.Println normally print to your terminal? Why does adding > output.txt send the same output to a file?
The answer starts with file descriptors.
A descriptor is a number, not a destination
On Unix-like systems, including macOS and Linux, a file descriptor, or fd, is an integer used to access an open I/O resource.
| fd | Stream | Usual interactive connection |
|---|---|---|
0 |
Standard input | Terminal |
1 |
Standard output | Terminal |
2 |
Standard error | Terminal |
Think of these as entries in a table maintained for each process. The numbers have conventional roles. Their connections can change.
These are Unix conventions. Native Windows APIs use handles, whose standard-output value need not be 1. Go hides this difference behind os.Stdout.
How Go wraps stdout
In the Unix-oriented standard-library code, stdout is initialized like this:
Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
Here, syscall.Stdout is 1. uintptr converts the number to the type required by NewFile. It is not a pointer to output data.
NewFile wraps the existing descriptor in an *os.File. It does not open /dev/stdout. That string is a name used by Name() and error reporting.
*os.File has a Write method matching io.Writer:
type Writer interface {
Write(p []byte) (n int, err error)
}
Go interfaces are satisfied implicitly. No explicit declaration is needed.
func greet(w io.Writer) error {
_, err := io.WriteString(w, "hello\n")
return err
}
// Inside a function:
err := greet(os.Stdout)
Accepting io.Writer makes the function reusable with files, buffers, and connections. The tradeoff is a narrow contract: writing alone does not promise flushing, seeking, or closing. Handle those responsibilities separately when needed.
The shell prepares redirection
./myapp > output.txt
The shell interprets >. A typical Unix implementation does the following:
- Creates a child process.
- Opens
output.txt, creating it or truncating its contents. - Makes fd
1refer to that open file. - Executes the application with the prepared descriptor.
The central operation is conceptually:
dup2(fd, 1); // Make fd 1 refer to fd's open resource.
Some shells use posix_spawn, an API that starts a program with configured file actions. It can perform equivalent descriptor setup.
The result is:
Parent shell: fd 1 → terminal
Go app: fd 1 → output.txt
The app writes to the file through its own fd. The shell does not normally receive the output and forward it. Changing the child’s descriptor table does not change the parent’s table.
Use >> output.txt to append instead. This preserves existing content, but the file can grow across runs.
stdout and stderr are separate
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("result")
fmt.Fprintln(os.Stderr, "diagnostic")
}
With ./myapp > output.txt, result goes to the file. diagnostic stays on the terminal, assuming stderr was connected there.
One Go detail matters: fmt.Println writes to stdout. The built-in println writes to stderr in the current Go implementation. Treat it as a debugging primitive, not a replacement for an application-output API.
Separate streams let another program consume results without diagnostics mixed in. Combining them gives you one convenient log, but loses that distinction.
2>&1 copies the current destination
To redirect both streams:
./myapp > output.txt 2>&1
2>&1 means “make fd 2 refer to the same destination as fd 1 right now.” Conceptually, that is dup2(1, 2).
In >&, the right-hand value is a descriptor number:
./myapp 2>1 # stderr goes to a file named "1".
./myapp 2>&1 # stderr goes to stdout's current destination.
Redirections run from left to right. Assuming stdout initially points to the terminal:
| Command suffix | stdout | stderr |
|---|---|---|
> output.txt 2>&1 |
File | File |
2>&1 > output.txt |
File | Terminal |
The second form first connects stderr to the terminal. It then changes stdout alone.
There is no permanent link from fd 2 to fd 1. After duplication, both entries refer to the same underlying resource. Changing one entry later does not move the other.
Sockets have descriptors too
On Unix, socket() returns an fd. A TCP client uses connect() to connect it to a peer. A server uses accept() to obtain a new fd for each accepted connection.
fd 3 → connected socket → remote host:443
The descriptor and the port are different. 3 identifies a resource inside a process. 443 identifies a network service endpoint. A socket’s fd is not always 3; available numbers are allocated and can be reused.
In Go, use net.Conn for normal networking. This function-body example uses io, net, and time:
conn, err := net.DialTimeout("tcp", "example.com:80", 5*time.Second)
if err != nil {
return err
}
defer conn.Close()
if err := conn.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
return err
}
_, err = io.WriteString(conn,
"GET / HTTP/1.0\r\nHost: example.com\r\n\r\n")
return err
On Unix, Go manages the socket descriptor internally. net.Conn also satisfies io.Writer.
net.Conn integrates deadlines and Go’s network poller. Raw descriptors offer lower-level control, but require more platform-specific code and resource management.
Descriptor numbers are local; resources can be shared
Each process has its own descriptor table:
Process A: fd 3 → socket
Process B: fd 3 → log file
Calling write(3, ...) in A does not use B’s descriptor.
However, resources can be shared. After fork(), the child inherits descriptors referring to the same underlying resources. Closing the child’s descriptor removes its reference. The parent’s descriptor remains usable.
Unix-domain sockets can also pass descriptors between processes, commonly through SCM_RIGHTS ancillary data:
Process A: fd 3 ──┐
├── same socket
Process B: fd 7 ──┘
The receiver gets a number in its own table. Sending the text 3 alone would not transfer access to the resource.
Sharing can avoid copying data through a middleman. It also shares underlying state. Reads from the same connected socket consume the same receive stream, so processes must coordinate who reads it.
Key takeaways
- An fd is a process-local number, not a destination or port.
os.Stdoutwraps standard output and satisfiesio.Writer.- The shell prepares redirection before the app starts.
>truncates the target file;>>appends.2>&1copies stdout’s current destination. Order matters.- Unix files, pipes, and sockets all use descriptors.
- Descriptor numbers are local, but underlying resources can be shared.