如何在sendfile函数中防止SIGPIPE

时间:2013-01-14 07:28:35

标签: c linux sockets signals

美好的一天,我有一个小的http服务器,我有线程池当前连接,当我在线程中发送文件我得到信号SIGPIPE和我的服务器崩溃。部分代码: //在线程中:

 detail::create_headers(headers,stat_buf.st_size,mime_types::extension_to_type(extension.c_str()));
    if(detail::write_to_client(fd_client,headers,unicode_strlen(headers))!=-1)
    {
        while(offset!=stat_buf.st_size)
        {
            if(sendfile(fd_client,src,&offset,stat_buf.st_size)==-1)
            {
                DEBUG_MSG_FORMAT("sendfile error: %d",errno);
                break;
            }
        }
    }
//和:

size_t write_to_client(int fd_client,const void *buf,size_t len)
{
    int optval = 1;
    setsockopt (fd_client, SOL_TCP, TCP_CORK, &optval, sizeof (int));
    size_t result = write(fd_client,buf,len);
    if(result==-1)
    {
        DEBUG_MSG_FORMAT("write error: %d",errno);
    }
    optval = 0;
    setsockopt (fd_client, SOL_TCP, TCP_CORK, &optval, sizeof (int));
                return result;
}
如何在线程中处理或阻止SIGPIPE?

1 个答案:

答案 0 :(得分:1)

  

如何在线程中处理或阻止SIGPIPE?

至少有三种方式:

  • 使用SO_NOSIGPIPE套接字选项
  • 使用MSG_NOSIGNAL({1}}(特定于Linux)
  • send(2)标志
  • 忽略sigpipe(使用SIG_IGN)或为其建立真正的处理程序

如果可能,我会选择第一个(它不可移植)。而不是信号,你将errno = EPIPE返回-1。