user1884325
user1884325

Reputation: 2550

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

Upvotes: 3

Views: 2920

Answers (6)

user2683747
user2683747

Reputation: 301

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.

Upvotes: 2

Perette
Perette

Reputation: 841

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)");
}

Upvotes: 3

Gaurav
Gaurav

Reputation: 2103

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

Upvotes: 0

Parag Bafna
Parag Bafna

Reputation: 22930

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");

}

Upvotes: 0

alk
alk

Reputation: 70931

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");
}

Upvotes: 2

Duck
Duck

Reputation: 27552

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

Upvotes: 2

Related Questions