Check on socket with select () returns 0 when data is present

I already had my socket class, but I wanted to add a timeout using select (). It seems pretty straight forward, but I always have 0 returned by the select () function. I even deleted check () so that it reads the data regardless of select () and the data is read, but select () still reports that there is no data. Any clue on how to get select () to stop lying to me? I also found that the socket is not blocking. Thanks.

the code:

char buf [ MAXRECV + 1 ]; s = ""; memset ( buf, 0, MAXRECV + 1 ); struct timeval tv; int retval; fd_set Sockets; FD_ZERO(&Sockets); FD_SET(m_sock,&Sockets); // Print sock int for sainity std::cout << "\nm_sock:" << m_sock << "\n"; tv.tv_sec = 1; tv.tv_usec = 0; retval = select(1, &Sockets, NULL, NULL, &tv); std::cout << "\nretval is :[" << retval << "]\n\n"; // Check if (FD_ISSET(m_sock,&Sockets)) std::cout << "\nFD_ISSET(m_sock,&Sockets) is true\n\n"; else std::cout << "\nFD_ISSET(m_sock,&Sockets) is false\n\n"; // If error occurs if (retval == -1) { perror("select()"); std::cout << "\nERROR IN SELECT()\n"; } // If data present else if (retval) { std::cout << "\nDATA IS READY TO BE READ\n"; std::cout << "recv ( m_sock, buf, MAXRECV, 0)... m_sock is " << m_sock << "\n"; int status = recv ( m_sock, buf, MAXRECV, 0 ); if ( status == -1 ) { std::cout << "status == -1 errno == " << errno << " in Socket::recv\n"; return 0; } else if ( status == 0 ) { return 0; } else { s = buf; return status; } } // If data not present else { std::cout << "\nDATA WAS NOT READY, TIMEOUT\n"; return 0; } 
+4
source share
2 answers

Your select call is incorrect, as you have already discovered. Despite the fact that the first parameter has the name nfds in many forms of documentation, it is actually one more than the largest file descriptor number that is stored in any of the fd_set passed to select . In this case, since you are passing only one file descriptor, the call should be:

 retval = select(m_sock + 1, &Sockets, NULL, NULL, &tv); 

If you have an arbitrary number of sockets that you process each in a different thread, you can find my answer to this question in a more suitable approach.

+4
source

Oops Looks like I forgot to set select () int nfds:

now works well.

0
source

All Articles