有人可以向我解释一下这段代码的粗体部分在做什么吗?
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 );
}
}
}
最佳答案
FD_ stuff 用于保留一组文件描述符,以并行处理不同“事件”的“等待”。第一个“粗体” block 用两个 fd、标准输入和套接字(可能)初始化该集合;然后“选择”函数使程序等待这些"file",当它们准备好读取时。当其中一个准备好时,select函数会交回控制权,但现在你无法知道哪个“fd”准备好了;因此 FD_ISSET 允许了解它并处理 if 主体中的情况并执行某些操作(其中之一或两者都可以准备好)。当stdin准备好被读取时,程序从中读取,然后写入sock;当 sock 准备好读取时,程序从中读取并将读取到的内容写入 stdout。
换句话来说,FD_ stuff 用于 I/O 复用。
关于C 语言的聊天客户端? (C网络编程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10100986/