Can someone explain to me what the bolded portions of this code are doing?
while ( 1 )
{
**FD_ZERO( &readfds );
FD_SET( 0, &readfds ); /* add stdin */
FD_SET( sock, &readfds );**
/* BLOCK on select() */
**select( FD_SETSIZE, &readfds, NULL, NULL, NULL );**
**if ( FD_ISSET( 0, &readfds ) )**
{
char msg[1024];
scanf( "%[^\n]", msg ); /* read everything up to the '\n' */
getchar(); /* read (skip) the '\n' character */
/* write the message to the socket connection */
int n = write( sock, msg, strlen( msg ) );
if ( n < strlen( msg ) )
{
perror( "write() failed" );
return EXIT_FAILURE;
}
}
**if ( FD_ISSET( sock, &readfds ) )**
{
char buffer[1024];
int n = read( sock, buffer, 1024 );
if ( n < 1 )
{
perror( "read() failed" );
}
else
{
buffer[n] = '\0';
printf( "Rcvd msg from server: %s", buffer );
}
}
}
The FD_ stuffs are used to keep a set of file descriptors to handle “waiting” on different “events” in parallel. The first “bold” block initializes the set with two fd, the standard input and a socket (likely); then the “select” function makes the program wait on those “files”, when they are ready to be read. When one of them is ready, the select function gives back control, but now you can’t know which “fd” was ready; so the FD_ISSET allows to know it and handle the situation in the body of the if and do something (one or both can be ready). When stdin is ready to be read, the program reads from it and then write to sock; when sock is ready to be read, the program reads from it and write what it has read to stdout.
Saying it differently, FD_ stuffs are for I/O multiplexing.