简体   繁体   中英

Select in C, why does it fail?

I'm reviewing a code in C with select(2) function. In this code, select function should return a number different from 0 when any of a set of two sockets it's ready. However it fails to find any file descriptor ready even though the sockets are declared just before the select and when I netstat --listen I get that one of the sockets (cmd_socket) is listening on its specified port. I've tried forcing different timeouts and I assume FD_SETSIZE is ok because this code used to work in another machine. What do is wrong? This is the code:

 // Program sockets intialization
int cmd_sock = create_and_bind_socket(cmd_port_property(0,GET) ,&src_addr);
mc_sock = create_and_bind_socket(mcast_port_property(0,GET), &mc_addr); 
join_multicast_group(mc_sock,mc_addr_str, &mc_req);


int recv_len = 0;
int childs = 0;

struct timeval tv;
struct timeval *ptv = &tv;

if (!timeout) {

  ptv = NULL;

} else {

  ptv->tv_sec = timeout;
  ptv->tv_usec = 0;

}

fd_set readfds, safe;
fdmax = mc_sock;

// Add multicast and unicast sockets to set
FD_ZERO(&readfds);
FD_SET(cmd_sock, &readfds);
FD_SET(mc_sock, &readfds);

safe = readfds;

// Wait until some socket on the set is ready to be read 
while(select (FD_SETSIZE,&readfds,NULL,NULL,ptv))  { 

Actually, the first argument to select(2) is the highest-numbered file descriptor in any of the three sets, plus 1 , not the FD_SETSIZE , which is just the number of bytes an fd_set takes.

Then zero return from select(2) means timeout expired. Check if you really have data on the wire, use tcpdump(1) or wireshark .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM