Ignore SIGPIPE process-wide with signal(SIGPIPE, SIG_IGN)
Writing to a closed pipe or socket kills the process with SIGPIPE. Ignore the signal and write(2) returns -1 with EPIPE, which you can handle in the code.
A server that writes to a client which has already hung up gets killed, silently, by SIGPIPE, whose default action is to terminate. For a program that handles many connections you want the error instead. Setting the disposition to SIG_IGN makes the write fail with EPIPE, as described in signal(7).
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(void) {
signal(SIGPIPE, SIG_IGN);
int fds[2];
if (pipe(fds) < 0) { perror("pipe"); return 1; }
close(fds[0]); /* no reader any more */
if (write(fds[1], "x", 1) < 0)
printf("write: %s\n", strerror(errno));
return 0;
}write: Broken pipeWithout the signal line the process dies at the write, with no output, and the shell reports it as exit status 141, which is 128 plus the signal number 13. The setting is process-wide and inherited across exec, so a program you start with SIGPIPE ignored keeps it ignored unless it resets it. That is why a command run in a shell pipeline and one run from a script can behave differently.
The blunt setting hides pipe errors in a command-line filter that should stop when its output closes, such as the left side of | head, so apply it in servers and not in simple tools. For a single socket you can leave the disposition alone and pass MSG_NOSIGNAL to send, which suppresses the signal for that call only. In a library, prefer that over changing a global setting that belongs to the application.