views:

47

answers:

1

I'm using the write() function to write to a socket in C. I am not a C expert, and sometimes I know this function can fail, in those cases it can return some kind of SIGPIPE.

Here's the simple piece of code I'm using now:

if(write(sockfd, sendline, sizeof(sendline)) < sizeof(sendline))
    {
        printf("Failed to write string %s to socket" , sendline);
        return NULL;
    }

My question is, how can I properly manage those kind of errors (SIGPIPE, etc) when using this function?

+4  A: 

As far as "how to handle errors", you need to check for the return value of write() being -1, and then if you want to distinguish between error conditions look at the value of errno.

In the specific case of SIGPIPE, this is delivered to a process if an attempt is make to write to a socket whose reading end is closed. By default, the delivery of SIGPIPE will cause the process to terminate. If you do not want this behaviour, then you will need to explicitly ignore SIGPIPE (signal(SIGPIPE, SIG_IGN)), and then the write() call will return -1 and errno will equal EPIPE.

Beano
Thanks for your response! , very clear !
Mr.Gando