Search code examples
clinuxmultithreadingsocketsblocking

When do writes on a socket block?


I'm writing a network application based on an epoll loop and thread pool for handling requests. In each thread I take special care not to block on client reads, by using non-blocking sockets and returning as soon as read returns EAGAIN (or EWOULDBLOCK to be POSIX compliant...).

Should I take special care in socket writes too? I don't see myself sending enough data to fill the system TCP buffers, and blocking for a while shouldn't be too harmful. Is this the only case where a write on a socket blocks? Not enough buffer size?

Also, can a socket be declared non-blocking for reads and blocking for writes? Or should I use fcntl all the time to switch between these behaviours?

Thanks!


Solution

  • The only case where a write on a socket blocks is when the data written won't fit in the buffer. Ideally, you would handle writes much the way you handle reads. You don't need to switch before each write. If you want to block on write, use this logic:

    1. Perform the write.

    2. If it completes, you're done.

    3. Switch the socket to blocking.

    4. Perform the (rest of) the write.

    5. Switch the socket back to non-blocking.