Search code examples
csocketsposix-select

Calling select() on a UDP socket gives an invalid argument error


I am calling select() on a UDP socket to see if there is data to be read. Every time the method returns -1 and errno is set to 22 (Invalid Argument). Here is part of my code:

fd_set sockets;
struct timeval alarm;
alarm.tv_sec = 0;
alarm.tv_usec = 1000;
FD_ZERO(&sockets);
FD_SET(udpSocket, &sockets);
maxfd = udpsocket + 1;
selected = select(maxfd, &sockets, NULL, NULL, &alarm);
printf("%d\n", selected);

"Selected" is always -1. I know that the socket is fine because at this point I have already successfully sent data over it.


Solution

  • It turns out that the reason for the error was that I was setting the microseconds property of the alarm to:

    alarm.tv_usec = 2000000;
    

    Which apparently is too high a value. Obviously, it was just easier to set the seconds property to 2:

    alarm.tv_sec = 2;