3

Is there a way to have 'select' waiting for reads and writes, while also being able to add new file descriptors? Preferrably on one thread?

poy
  • 10,063
  • 9
  • 49
  • 74

2 Answers2

3

As far as I think, You can do it in same thread but not at the same time. In a problem like this I normally add my dummy loop-back socket in the descriptor list and whenever I have to add a new socket in FD_LIST, I just send a byte to my dummy socket and it breaks the Select Loop. Then I can update the FD_LIST and resume with the select again.

Tayyab
  • 9,951
  • 1
  • 16
  • 19
  • You can also add a timeout to the `select` call using the last parameter. – André Caron Apr 11 '11 at 20:11
  • Yes of course. But in that case if you are using long time interval in select then you have to wait until your new socket is added to the FD_LIST. If you are using very short interval in select or you don't need to add socket immediately then using the interval parameter is good option. – Tayyab Apr 11 '11 at 20:17
3

Now that I know what your scenario is (a socket-based server that may want to accept new incoming connections), did you know that you can append the file-descriptor for your listening socket to the list for select? See e.g. http://www.lowtek.com/sockets/select.html.

(Paraphrased example:)

fd_set socks;

FD_ZERO(&socks);

// Add listener socket
listen(sock, n);
FD_SET(&socks, sock);

// Add existing socket connections
for (i = 0; i < num_existing_connections; i++)
{
    FD_SET(&socks, connection[i]);
}

// Will break if any of the existing connections are active,
// or if a new connection appears.
select(..., &socks, ...);
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680