How to Fix ‘Broken Pipe’ (EPIPE) Error in Linux

Working within the Linux terminal, executing remote automation scripts, or maintaining long-running SSH sessions frequently leads to an abrupt interruption accompanied by the message: “Broken pipe”, “packet_write_wait: Connection to x.x.x.x port 22: Broken pipe”, or programmatic error code EPIPE (errno 32). This error occurs at the kernel level whenever a process attempts to write data to a UNIX pipe, FIFO, or network socket whose reading end has already been closed. When the operating system detects a write operation to an orphaned buffer, the Linux kernel raises a SIGPIPE signal, abruptly killing the writing process unless explicit signal handling or network keepalive mechanisms are configured. This guide breaks down why broken pipe errors occur and demonstrates practical configurations to resolve them across SSH, shell pipelines, and networked applications.

What Triggers a Broken Pipe (EPIPE) in Linux?

The Linux virtual filesystem and socket layers enforce strict IPC (Inter-Process Communication) contracts:

  • Premature Downstream Termination in Shell Pipes: When chaining commands (e.g., cat large_file.log | head -n 10), the receiving utility (head) exits as soon as its condition is satisfied. When the upstream utility (cat) attempts to send more bytes, the kernel issues SIGPIPE.
  • Dead Peer Disconnection in SSH: When idle remote SSH connections experience stateful firewall or NAT gateway session timeouts, intermediate routers drop the TCP connection silently. The next packet sent from your client yields a broken pipe error.
  • Network Socket Teardowns: In client-server architectures, if the server crashes or closes its socket while the client continues transmitting payload buffers, write() or send() returns -1 with errno = EPIPE.
  • Buffer Overflow and Resource Starvation: Heavy I/O workloads exhausting kernel socket buffer allocation causing premature socket termination.

Method 1: Prevent SSH ‘Broken Pipe’ Errors with Keepalive Settings

The most widespread manifestation of this error occurs during idle SSH terminal sessions. Configuring automated client-side and server-side keepalive pulses ensures NAT firewalls do not terminate your session.

Client-Side Configuration (Recommended):

  1. Open your local SSH client configuration file in a text editor:
    nano ~/.ssh/config
  2. Add or modify the host definition block with the following directives:
    Host *
        ServerAliveInterval 60
        ServerAliveCountMax 3
        TCPKeepAlive yes
  3. Save the file (Ctrl + O, then Enter) and exit (Ctrl + X).
  4. Explanation: ServerAliveInterval 60 instructs your SSH client to send an encrypted null packet to the server every 60 seconds of inactivity. If three consecutive pulses fail (ServerAliveCountMax 3), the client terminates cleanly rather than hanging.

Server-Side Configuration (Optional):

  1. On the remote Linux server, edit the SSH daemon configuration:
    sudo nano /etc/ssh/sshd_config
  2. Configure:
    ClientAliveInterval 60
    ClientAliveCountMax 3
  3. Restart the SSH service:
    sudo systemctl restart sshd

Method 2: Handle Broken Pipes Gracefully in Shell Scripts

When writing Bash scripts that process large data streams through pipelines, you can manage or suppress SIGPIPE signals depending on your programmatic requirements.

Example: Piping Data to Utilities That Exit Early

If you run a script that streams endless data into a reader that exits after processing a slice, standard error output displays broken pipe warnings:

# Without handling, this produces 'cat: write error: Broken pipe'
cat /var/log/syslog | head -n 5

To silence benign pipeline termination in automated scripts, redirect standard error of the writing process to /dev/null, or trap the signal:

# Redirect stderr to prevent noisy logs
cat /var/log/syslog 2>/dev/null | head -n 5

# Or check PIPESTATUS in Bash to handle exits conditionally
command1 | command2
echo "Exit codes: ${PIPESTATUS[0]} and ${PIPESTATUS[1]}"

Method 3: Utilize Terminal Multiplexers (tmux or screen)

If your work involves long-running compilations, database migrations, or remote backups over WAN connections, never run them directly in a raw SSH shell. If the network drops and produces a broken pipe, the kernel kills your running jobs.

  1. Install tmux on your Linux system:
    sudo apt install tmux    # Debian / Ubuntu
    sudo dnf install tmux    # RHEL / Fedora
  2. Start a persistent session before launching your workload:
    tmux new -s maintenance
  3. Run your critical tasks inside this virtual session.
  4. If your SSH connection suffers a broken pipe, your tasks continue running uninterrupted in the background on the server.
  5. Reconnect via SSH and reattach to the session:
    tmux attach -t maintenance

Method 4: Tune Kernel TCP Keepalive Parameters via sysctl

For high-throughput servers and database nodes experiencing socket teardowns, tuning Linux kernel TCP keepalive timings maintains socket resilience.

  1. Inspect your current kernel TCP keepalive parameters:
    sysctl net.ipv4.tcp_keepalive_time net.ipv4.tcp_keepalive_intvl net.ipv4.tcp_keepalive_probes
  2. By default, tcp_keepalive_time is set to 7200 seconds (2 hours), which is far too long for modern firewalls that drop state tables after 5 to 10 minutes of silence.
  3. Edit /etc/sysctl.conf:
    sudo nano /etc/sysctl.conf
  4. Append the following optimized socket directives:
    net.ipv4.tcp_keepalive_time = 300
    net.ipv4.tcp_keepalive_intvl = 60
    net.ipv4.tcp_keepalive_probes = 5
  5. Apply the new parameters immediately without rebooting:
    sudo sysctl -p

Method 5: Handling EPIPE in Application Code (C, Python, Node.js)

If you are developing networked tools or backend services, handle SIGPIPE gracefully to prevent unexpected process crashes.

  • In C/C++: Use the MSG_NOSIGNAL flag when calling send():
    send(sockfd, buffer, len, MSG_NOSIGNAL);
    Alternatively, ignore the signal globally: signal(SIGPIPE, SIG_IGN);.
  • In Python: Catch BrokenPipeError (or IOError):
    try:
        sys.stdout.write(data)
    except BrokenPipeError:
        # Python flushes stdio buffers on exit; redirect to devnull
        devnull = os.open(os.devnull, os.O_WRONLY)
        os.dup2(devnull, sys.stdout.fileno())
        sys.exit(1)
  • In Node.js: Attach an error listener to writable streams:
    stream.on('error', (err) => {
      if (err.code === 'EPIPE') {
        // Handle closed downstream socket gracefully
      }
    });

EPIPE and Broken Pipe Diagnostics

Scenario Trigger Mechanism Primary Resolution
SSH Remote Terminal Firewall NAT idle drop ServerAliveInterval 60 in ~/.ssh/config
Shell Pipeline Reader utility exited early Redirect stderr or inspect PIPESTATUS
Long-Running Jobs Process killed on network drop Run inside tmux or screen
Server Sockets Outdated TCP keepalive sysctl net.ipv4.tcp_keepalive_time=300

Configuring SSH keepalive intervals and terminal multiplexers ensures your Linux command-line operations remain stable and impervious to unexpected socket termination.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.