I’ve run into a rather strange problem:
I use select() in order to determine if a socket becomes readable. However, whenever a client connects, I get a segfault when I call FD_ISSET() to check if a given socket is present in the fd_set.
/* [...] */
while( /* condition */ ){
timeout.tv_sec = 0;
timeout.tv_usec = SELECT_TIMEOUT;
//this simply fills sockets with some file descriptors (passed in by clients - both parameters are passed by reference)
maxfd = this->build_fd_set( clients, sockets );
//wait until something relevant happens
readableCount = select( maxfd + 1, &sockets, (fd_set*)NULL, (fd_set*)NULL, &timeout );
if( readableCount > 0 ){
//Some sockets have become readable
printf( "\nreadable: %d, sockfd: %d, maxfd: %d\n",
readableCount, this->sockfd, maxfd );
//Check if listening socket has pending connections
// SEGFAULT OCCURS HERE
if( FD_ISSET( this->sockfd, &sockets ) ) {
DBG printf( "new connection incoming" );
this->handle_new_connection( clients );
/* [...] */
}else {
// Data is pending on some socket
/* [...] */
}
}else if( readableCount < 0 ) {
//An error occured
/* [...] */
return;
}else {
// select has timed out
/* [...] */
}
}
EDIT:
Yeah, sorry for the sparse info: I’ve updated the code.
this->sock_fd is set up to be a descriptor for a listening socket, created usingthis->sockfd = socket( AF_UNIX, SOCK_STREAM, 0 ); and then made listening via listen( this->sockfd, ACCEPT_BACKLOG ).
build_fd_set:
int SvcServer::build_fd_set( const vector<int>& clients, fd_set& sockets ) {
//build up the socket set
FD_ZERO( &sockets );
FD_SET( this->sockfd, &sockets ); //listening socket is always part of the set
int maxfd = this->sockfd;
//Add all currently connected sockets to the list
for( vector<int>::const_iterator it = clients.begin() ; it != clients.end() ; ++it ) {
FD_SET( *it, &sockets );
maxfd = max( maxfd, *it );
}
return maxfd;
}
It really doesn’t matter what clients is, it’ just empty and meant to be filled once clients connect, which is not happening since the whole thing segfaults on the first incoming connection.
Also, here’s some sample output:
readable: 1, sockfd: 3, maxfd: 3
Segmentation fault
The things I can derive here are:
- The call to
select()works,readableis set correctly - Also
sockfdandmaxfdare valid descriptors.
I’m afraid I can’t provide you with any debugging info (e.g. gdb) since I’m cross compiling and gdb is not available on the platform I’m compiling to.
Nevermind, I figured it out. * stupid me *
Turns out, the segfault was never actually occuring at the suspected position, the last printf before the segfault never got shown because it stdout wasn’t flushed. The actual segfault occured a little later and was (of course) my mistake.
thx nevertheless