Our professor gave us this code in class:
st = select(max+1, &rs, NULL, NULL, &timeinterval);
if(st){
for(int i=0; i<workers; i++)
{
if(FD_ISSET(channels[i]->read_fd(), &rs))
and I honestly have a hard time trying to understand what it's doing. I've tried to research more about pthreads but nothing seems to show up to explain what this is doing. He says it has something to do with file descriptors but I don't get how this is being in this code.
The purpose of this select
is to wait on multiple file descriptors, with a possibly time out, when it returns with a positive number, that means at least one fd in the rs
set becomes ready for reading, so that in a loop, you check which fd is it, and performs read on it.
Note, you should check for bigger than 0 instead, because -1 will be returned in case of error, which you should not check the fd_set but handle the error:
if(st > 0) {
for(int i=0; i<workers; i++)
{
if(FD_ISSET(channels[i]->read_fd(), &rs)) {
// perform read on channels[i]->read_fd
}
}
} else if (st == 0) {
// handle time out
} else {
// handle error
}