So I totally lost it when someone showed me some code using select() like:
FD_ZERO(&readfds);
FD_SET(socket,&readfds);
FD_SET(0,&readfds);
.......// bind() and listen(),regular stuff
// Before select(),this guy cleared readfds to null and sort of start all over again
FD_ZERO(&readfds);// Behold,this is exactly the line confusing myself
FD_SET(socket,&readfds);
// select will be called in the future within a infinite loop
So basically saying what FD_ZERO
after bind and listen is clear previous contents for some reason and insert socket file descriptor to fd set again.Meanwhile,in fd set,the 0 descriptor(standard input) apparently disappeared.
Could anyone explain this whole thing? I don't feel like this is correct but i cant really figure it out. Maybe setting up some specific fd set all over again is a practical mechanism...
I thought bind()
and listen()
could modify fd set in some sort of manner.I set up a couple of breaking points and examine the outputs.Consequently,fd set did not change at all.
UPDATE:
What really confuses me is the second FD_ZERO(&readfds)
.
Obviously the first one is like clearing rusty stuff in the buffer. On each iteration,we have to clear fdset to default for the future. I just dont understand the second one. Either it is a wrong one or it wont hurt at any rate.
select
will change the fdset, butbind
andlisten
can't, they aren't even given a pointer to it. But do yourself a favor and use a modern API likepoll
orepoll
and don't worry about fdset ever again.poll
. It's modern and portable and fast.epoll
is only for benchmark self-pleasuring and the benchmarks it excels in do not correspond to most real-world use needs (whereepoll
is actually much slower thanpoll
).