Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why FD_SET/FD_ZERO for select() inside of loop?

Tags:

I am using the select function for communication between my sockets. I have a while loop and I do -

    while(!done) {      FD_ZERO(&read_flags);     FD_ZERO(&write_flags);     FD_SET(comm_fd1, &read_flags);     FD_SET(comm_fd2, &read_flags);     FD_SET(STDIN_FILENO, &read_flags);     FD_SET(comm_fd1, &write_flags);     FD_SET(comm_fd2, &write_flags);     FD_SET(STDIN_FILENO, &write_flags);      //call select     sel = select(comm_fd1+comm_fd2+1, &read_flags, &write_flags, (fd_set*)0, &waitd); 

and the same with different variables on the client side. I got this basic technique from a tutorial online and just went with it. Then it hit me - why do I clear the set and add file descriptors each time I loop? If they are already added, why clear them and add again? So I tried only doing this once before the while, and the code does not work the same anymore. Can someone explain why? Is it just because select modifies the contents of the set? Any help and/or insight is appreciated.

like image 969
Sterling Avatar asked Oct 03 '11 16:10

Sterling


People also ask

What does Fd_zero do?

This function initializes the file descriptor set to contain no file descriptors.

What is fd_set used for?

The fd_set structure is used by various Windows Sockets functions and service providers, such as the select function, to place sockets into a "set" for various purposes, such as testing a given socket for readability using the readfds parameter of the select function.

What does select () do in C?

The select() function indicates which of the specified file descriptors is ready for reading, ready for writing, or has an error condition pending.


1 Answers

When select returns, it has updated the sets to show which file descriptors have become ready for read/write/exception. All other flags have been cleared.

It's important that you re-enable the file descriptors that were cleared prior to starting another select, otherwise, you will no longer be waiting on those file descriptors.

As for re-clearing, it can be a good habit to get into, since if you need to change the set of file descriptors (such as adding a newly opened socket to the read set), you'll want to clear it and rebuilt it every time, so that it's correct as the state of the program changes.

like image 187
Dave S Avatar answered Sep 30 '22 17:09

Dave S