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?
Asked
Active
Viewed 1,596 times
3
-
If you only have one thread, then who is adding the new file descriptors? – Oliver Charlesworth Apr 11 '11 at 20:06
-
@Oli: I think OP just wants to cancel the `select` call and add the descriptor before another call to `select` is made. – André Caron Apr 11 '11 at 20:09
-
1@Andre: But with only one thread, *when* does he want to break the `select`? Is there some external stimulus? – Oliver Charlesworth Apr 11 '11 at 20:11
-
@Oli: Well I'm actually using sockets. So more clients may be connecting. – poy Apr 11 '11 at 20:15
-
@Andrew: But presumably your listening socket is part of that select, so when a new client connects the select *does* return, allowing you to change the fd set for the next call. – Greg Hewgill Apr 11 '11 at 20:19
-
@Greg: I didn't realize that select would return when you get a new client. This DEFINATELY clears things up. Thanks again. – poy Apr 11 '11 at 20:55
2 Answers
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