简体   繁体   中英

How to prevent SIGPIPE in sendfile function

Good day i have small http server where i have threadpool current connections, when i do send file in thread i get signal SIGPIPE and my server crash. Part of code: //in thread:

 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;
            }
        }
    }
//and:
 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; }
How can i handle or prevent SIGPIPE in thread?

How can i handle or prevent SIGPIPE in thread?

At least three ways:

  • Use the SO_NOSIGPIPE socket option
  • Use the MSG_NOSIGNAL flag for send(2) (Linux-specific)
  • Ignore the sigpipe (using SIG_IGN ) or establish a real handler for it

I would go for the first one if possible (it's not portable). Instead of the signal you'll get a return of -1 with errno = EPIPE .

Seemingly, sendfile() does not have any flags (like eg send() does with MSG_NOSIGNAL ), so one option is to disable SIGPIPE using signal(SIGPIPE, SIG_IGN) , but that does not keep debuggers like gdb to stop your process on SIGPIPE . If you want gdb to keep your code running, try handle SIGPIPE nostop in gdb or replace sendfile() by a read/send loop with MSG_NOSIGNAL flags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM