Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select() not working for me

I have a problem, i use select function to wait when i can read received data on server side, but it works wrong like i receive nothing and timeout passed.

Server side code:

 int fd = accept(sockfd, addr, addrlen);
 if(fd > 0)
 {
     struct timeval tv;
     fd_set rfds;
     FD_ZERO(&rfds);
     FD_SET(fd, &rfds);

     tv.tv_sec = 5;
     tv.tv_usec = 0;
     // wait when i can read data
     int ret_select = select(1, &rfds, (fd_set *) 0, (fd_set *) 0, &tv);
     if(ret_select > 0)
     {
         // data ready to be readed. NEVER HERE!
     }
     else
     {
        // nothing. ALWAYS HERE
     }
    }

Client side:

int ret = connect(s, name, namelen);
if(ret == 0)
{
 struct timeval tv;
 fd_set rfds;
 FD_ZERO(&rfds);
 FD_SET(s, &rfds);

 tv.tv_sec = 5;
 tv.tv_usec = 0;
 // wait when we can write
 int ret_select = select(1, (fd_set *) 0, &rfds, (fd_set *) 0, &tv);
 if(ret_select > 0)
 {
  int sended = send(s, my_data, size_data, 0);
  if(sended > 0)
  {
   // all ok, data sended!
  }
 }
}

But if i remove on server side calling select - all ok, data to read is exists, so i guess select works wrong in my code!

Whats wrong with my code?

Thanks!

like image 667
Becker Avatar asked Jan 26 '26 10:01

Becker


1 Answers

The first argument of select() is not the number of file descriptors in the set. It is:

nfds is the highest-numbered file descriptor in any of the three sets, plus 1.

So, unless your socket file descriptor is number 0, your argument of 1 is wrong.

like image 61
unwind Avatar answered Jan 29 '26 00:01

unwind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!