DB / Linux / 13
WARNING

Linux SIGPIPE (Broken Pipe)

SIGPIPE is sent to a process when it attempts to write to a pipe, socket, or FIFO that has no readers (the reading end is closed). The default action is to terminate the process.

Common Causes

  • Writing to a pipe where the reading process has terminated or closed its end
  • Network socket connection closed by the remote peer while writing data
  • Child process exiting without reading from a pipe created by the parent
  • Programs like 'head' or 'grep' closing their input after matching criteria, causing upstream processes to receive SIGPIPE

How to Fix

1 Ignore SIGPIPE Signal

Make your program ignore SIGPIPE signals to prevent termination. The write operation will still fail with EPIPE error.

BASH
$ signal(SIGPIPE, SIG_IGN); // C example # Or in shell scripts: trap '' PIPE

2 Check Write Return Values

Always check return values of write() system calls and handle EPIPE errors gracefully instead of crashing.

BASH
$ ssize_t bytes_written = write(fd, buffer, size); if (bytes_written == -1 && errno == EPIPE) { // Handle broken pipe gracefully close(fd); // Clean up resources }

3 Use MSG_NOSIGNAL Flag (Sockets)

For socket programming, use MSG_NOSIGNAL flag with send() to prevent SIGPIPE generation on broken connections.

BASH
$ send(socket_fd, buffer, buffer_size, MSG_NOSIGNAL);

4 Pipe Handling in Shell

In shell scripts/pipelines, ensure all processes in the pipeline handle termination properly.

BASH
$ # Use 'trap' to handle signals #!/bin/bash trap 'cleanup' EXIT ERR SIGTERM SIGPIPE cleanup() { echo "Cleaning up..." # Close file descriptors, remove temp files } # Or use 'set' to ignore certain signals set -o pipefail # Capture pipeline failures without SIGPIPE