I can't think of an easy way for the signal handler to come to know the current socket being processed unless you are setting some global state each time you do a socket operation.
You can ignore SIGPIPE
from main. You do not define your own handler, instead you use SIG_IGN
.
signal(SIGPIPE, SIG_IGN);
Or, if you are using sigaction
:
struct sigaction act;
act.sa_handler = SIG_IGN;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGPIPE, &act, NULL);
Alternatively, you can issue the MSG_NOSIGNAL
flag when you call send. This will suppress the generation of SIGPIPE
, and instead generate an EPIPE
error (which is what would happen if you ignored SIGPIPE
):
ssize_t sent = send(sock, buf, sizeof(buf), MSG_NOSIGNAL);
if (sent > 0) {
/* ... */
} else {
assert(sent < 0);
swtich (errno) {
case EPIPE:
/* ...handle sending on a closed socket */
/* ...handle other error cases */
}
}