As mentioned by Apple, in Avoiding Common Networking Mistakes, you need to handle or disable SIGPIPE
:
Use POSIX sockets efficiently (if at all).
If you are using POSIX sockets directly:
- Handle or disable SIGPIPE.
When a connection closes, by default, your
process receives a SIGPIPE
signal. If your program does not handle or
ignore this signal, your program will quit immediately. You can handle
this in one of two ways:
Ignore the signal globally with the following line of code:
signal(SIGPIPE, SIG_IGN);
Tell the socket not to send the signal in
the first place with the following lines of code (substituting the
variable containing your socket in place of sock
):
int value = 1;
setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, &value, sizeof(value));
For maximum compatibility, you should set this flag on each incoming
socket immediately after calling accept in addition to setting the
flag on the listening socket itself.