开发者

How to properly use the write() function for sockets?

开发者 https://www.devze.com 2022-12-19 01:10 出处:网络
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.

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 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号