shtux
shtux

Reputation: 1

select in c shows strange behaviour

I wrote some code, that should iterate over a list of sockets, send packets to them and if it got an answer, send it back to a specific socket.

Here is the snippet of my code:

 while ((curr_fd = conn_get_node()) > 0) {
   
   send(curr_fd, fifo_packet.packet, MSGLENGTH, 0);

   FD_ZERO(&rfds);
   FD_SET(curr_fd, &rfds);

   got_answer = select(curr_fd + 1, &rfds, NULL, NULL,
                   &tv);

   if (got_answer == -1) {
           perror("select()\n");
   } else if (got_answer == 1) {
           get_packet(curr_fd, &answer);
           send(fifo_packet.from_fd, &answer, MSGLENGTH, 0);


   } else {
           printf("no data within 100us\n");
           continue;
}

Now it shows that for the first two or three packets sent, select will always say, that it did not receive anything (got_answer = 0) although I can see that data has arrived with a sniffer. After about the third packet it starts to work (got_answer = 1).

Does anybody have an idea what I am doing wrong?

Upvotes: 0

Views: 76

Answers (1)

unwind
unwind

Reputation: 399823

You are not checking when select() returns that the fd is still in the "ready for read"-set. Use FD_ISSET() to check this. This is needed since select() can return for other reasons than data being available.

Upvotes: 2

Related Questions