Why use writefds in select ? How to use them in practice? Why use writefds in select ? How to use them in practice? multithreading multithreading

Why use writefds in select ? How to use them in practice?


The writefds of select is to check that the file descriptor is ready for writing. For a socket that means that the send buffer associated with the socket is not full.

Let's assume that the sockets on your platform have an 8 kb buffer and you want to send 100 kb of data.

You call write and get a return value of 8192 indicating that the first 8192 bytes have been written. The next call to write returns either EAGAIN or EWOULDBLOCK indicating that the send buffer is full.

You can now use select to find out when there is room in send buffer again (that is, when one tcp/ip packet has been transferred to the client) so that you can continue writing. At the same time you can be listening for new connections and waiting for input from clients.

Note that select never sends any data, it just monitors the status of several file descriptors at once.


No, select() will not "take care of writing". It will notify you when one or more of the file descriptors included in the writefds set becomes writable. This can mean that the fd(s) in question have finished the previous (non-blocking) write you did, so that you can now do another.


select() tells you when a file descriptor is writable. For a socket, that means it can accept new outbound data without blocking the caller. If you call send() or write() and the socket's outbound buffer is full, you will get an EAGAIN or EWOULDBLOCK error, at which time you would stop writing to that socket until it becomes writable again. select() can also tell you when the socket becomes writable after a non-blocking connect() is called, indicating a successful connection has been made and data can start being written to the peer.