heruma
heruma

Reputation: 41

How to avoid a broken pipe?

I try to develop a chat application in c. I use sockets and select(). But if i close the server before the client, the client have a message "Broken Pipe". I used select(), but i didn't know how to avoid it?

Upvotes: 4

Views: 2444

Answers (2)

Valeri Atamaniouk
Valeri Atamaniouk

Reputation: 5163

You can disable the signal:

signal(SIGPIPE, SIG_IGN);

Though the chosen answer was to ignore signal process wide, there are other alternatives:

Using send function with MSG_NOSIGNAL:

 send(con, buff_enviar+enviado, length-enviado, MSG_NOSIGNAL);

Disabling SIGPIPE on socket level (not available on all kernels):

int flag = 1;
setsockopt(con, SOL_SOCKET, SO_NOSIGPIPE, &flag, sizeof(flag));

Disabling SIGPIPE for caller thread (you can restore it after):

sigset_t set;
sigemptyset (&set);
sigaddset (&set, SIGPIPE);
pthread_sigmask(SIG_BLOCK, &set, NULL);

Upvotes: 5

Kerrek SB
Kerrek SB

Reputation: 477484

Register a handler for the PIPE signal (and maybe ignore the signal).

Upvotes: 0

Related Questions