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?
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 oferrno.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 ofSIGPIPEwill cause the process to terminate. If you do not want this behaviour, then you will need to explicitly ignoreSIGPIPE(signal(SIGPIPE, SIG_IGN)), and then thewrite()call will return-1anderrnowill equalEPIPE.