我在选择中使用read()时遇到问题 [英] I have a question when i use read() in select
问题描述
你好,当我使用select()和read()时,我有一个问题.
关键代码是:
hello , i have a question, when i use select() and read().
the key codes is :
nready = select( maxfd + 1, server->fd_readset, 0, 0, timeout );
if( nready > 0 )
printf( "nready is %d\n", nready );
char buf[100];
int n ;
if ( FD_ISSET( server->fd , server->fd_readset ) ) /* new client connection */
{
int s = (int)accept( server->fd, 0, 0 );
if ( s == -1 )
{
printf( " errno is %d\n", errno );
fprintf( stdout, "error is %s\n", strerror( errno ) );
}
printf( "s is %d\n", s );
for ( j = 0; j < FD_SETSIZE; j++ )
{
if ( client[j] < 0 )
{
if( s > 0 )
client[j] = s; /* save descriptor */
break;
}
}
if ( j == FD_SETSIZE )
{
printf( "too much clients!\n" );
}
FD_SET( s, server->fd_set ); /* add new descriptor to set */
if( s > maxfd )
maxfd = s; /* for select */
if( j > maxi )
maxi = j; /* max index in client[] array */
if( --nready <= 0 )
continue;
}
/*printf( "client[0] is %d\n", client[0] );*/
for( j = 0; j <= maxi; j++ )
{
if( ( sockfd = client[j] ) < 0 )
continue;
if( FD_SET( sockfd, server->fd_readset ) )
{
if( ( n = read( sockfd, buf, 100) ) != 0 )
{
问题是:我启动了服务器,但是我只允许一个客户端通过write()函数将消息发送到服务器.另一个客户端无法发送消息.
我已经用gdb调试了,我发现服务器在read()中阻塞了;服务器仍然读取第一个客户端.
我尝试使用alarm()来解决它,但是不起作用.当read()超时时,它仍然处于阻塞状态.
请告诉我为什么?谢谢.
the question is: i start up the server, but i just let only one client send messages to server by function of write(). the another client can''t send messages.
i have debug by gdb, i found the server is blocking in read(); the server still read the first client.
i try to use alarm() to solve it, but it don''t work.when the read() make the time out, it''s still blocking.
please tell me why? thank you.
推荐答案
服务器通过bind()
连接到恰好一个客户端.如果要侦听另一个客户端,则必须绑定一个新套接字以连接传入的接受请求.因此,必须对每个绑定的套接字使用线程,因为请求是异步的.
问候.
The server is connected by thebind()
to exactly one client. If you want to listen for another client you have to bind a new socket to connect on incoming accept requests. Therefore you have to use threads for each bound socket, because the requests are async.
Regards.
这篇关于我在选择中使用read()时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!