简体   繁体   中英

SIGPIPE (OSX) and disconnected sockets?

I'm working on an app which connects to a server via TCP.

If the socket for whatever reason is closed, I end up in the SIGPIPE handler.

What do I do so that recv and send just returns an error on a disconnected/closed socket?

Thanks

I've found ignoring SIGPIPE ineffective on OS X. Use SO_NOSIGPIPE instead. Note this is set on the socket once, as opposed to MSG_NOSIGNAL which is requested in each call to send().

int socket = accept (...); /* (or however you're getting the socket) */
int option_value = 1; /* Set NOSIGPIPE to ON */
if (setsockopt (socket, SOL_SOCKET, SO_NOSIGPIPE, &option_value, sizeof (option_value)) < 0) {
    perror ("setsockopt(,,SO_NOSIGPIPE)");
}

SIG_IGN the signal rather than handling it. send will return -1 and errno will be set to EPIPE.

To ignore a signal set the signal handler to SIG_IGN doing so:

struct sigaction sa;
memset(&sa, 0, sizeof(sa));

sa.sa_handler = SIG_IGN;

if (-1 == sigaction(SIGPIPE, &sa, NULL))
{
  perror("sigaction() failed");
}

Ignoring SIGPIPE as described in other answers (ie. signal(SIGPIPE, SIG_IGN); ) worked for me on OS X. Also be sure to test outside a debugger as it says in this comment . I was debugging with lldb and its signal handling was terminating my program with SIGPIPE even though I'd ignored that signal. Testing outside of lldb worked fine.

use signal handler or ignore it

#include <signal.h>
signal(SIGPIPE, SIG_IGN);

while writing to a socket first check if socket fd is positive or not in program. Externally you should check that you are sending pointer of a valid socket

You can ignore SIGPIPE

 #include <signal.h>

signal(SIGPIPE, SIG_IGN);

Or you can use signal handler.

signal(SIGPIPE, handler);
void handler(int signal)
{   
    //("Signal caught");

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM