Call to select() function with more than 247 socket descriptors added to read descriptor set results in error
See the attached code example (also added to ‘How to reproduce’) whereby variable NR_RFDS set to an value higher than 247 results in an error “Bad file descriptor”.
This limit seems not to exist for, for example, pipes and open files.
What is the reason for this limit? How can this limit be removed?
How to Reproduce Code example:
[code]#ifdef FD_SETSIZE
#undef FD_SETSIZE
#endif
#define FD_SETSIZE 1000
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/socket.h>
#define NR_RFDS 248
int main( void )
{
int fd_array[NR_RFDS];
struct timeval tv;
fd_set rfd;
int n, rfd_max = 0;
for( n = 0; n < NR_RFDS; n++ )
{
fd_array[n] = socket(AF_INET, SOCK_STREAM, 0);
if (fd_array[n] < 0)
{
perror( “open” );
return EXIT_FAILURE;
}
}
FD_ZERO( &rfd );
for( n = 0; n < NR_RFDS; n++ )
{
FD_SET( fd_array[n], &rfd );
if( fd_array[n] > rfd_max )
{
rfd_max = fd_array[n];
}
}
tv.tv_sec = 1;
tv.tv_usec = 0;
switch ( n = select( 1 + rfd_max, &rfd, 0, 0, &tv ) )
{
case -1:
perror( “select” );
return EXIT_FAILURE;
case 0:
puts( “select timed out” );
break;
default:
printf( “%d descriptors ready …\n”, n );
for( n = 0; n < NR_RFDS; n++ )
{
if( FD_ISSET( fd_array[n], &rfd ) )
{
printf( " – %d descriptor has data pending", fd_array[n] );
}
}
}
return EXIT_SUCCESS;
}
[/code]
Run:
./example
select: Bad file descriptor