You need to initialize the sets in the loop, every time before calling select
. This is needed because select
modifies them. Beej's Guide to Network Programming has a comprehensive example on one way to use select
.
So in your code, it seems select
returns first with writing allowed, but reading not, which has the read bit reset to 0, and then there's nothing to set it back to 1, because from then on select
will not touch it, because it is already 0.
If select
API bothers you, look at poll
, it avoids this (note that there's probably no practical/efficiency difference, it basically boils down to personal preference). On a "real" code with many descriptors (such as a network server with many clients), where performance matters, you should use some other mechanism though, probably some higher level event library, which then uses the OS specific system API, such as Linux's epoll facility. But checking just a few descriptors, select
is the tried and true and relatively portable choice.