accept阻塞

一直以来以为accept阻塞的时候,若另有线程关闭相应的监听套接字,accept会立即返回。

今天先是在NDK上试,没反应。又在ARCHLINUX试了下,还是没反应。难道是我一直记的都是错的!!!!!!!!!!!!!!!!写下来,以做备忘,同时写一份非阻塞的ACCEPT

 

 1 int tcp_accept_timed( int fd, int msecs )
 2 {
 3     int rc, connfd;
 4     struct timeval tv;
 5     fd_set rset;
 6     struct sockaddr_in sin;
 7     socklen_t len;
 8 
 9     do
10     {
11         tv.tv_sec = msecs / 1000;
12         tv.tv_usec = ( msecs % 1000 ) * 1000;
13 
14         FD_ZERO( &rset );
15         FD_SET( fd, &rset );
16     }
17     while ( ( rc = select( fd + 1, &rset, NULL, NULL, &tv ) ) == -1 && errno == EINTR );
18     if ( rc < 1 )
19     {
20         if ( rc == -1 )
21         {
22             perror( "select" );
23         }
24         return -1;
25     }
26 
27     len = sizeof( struct sockaddr_in );
28     memset( &sin, 0, len );
29     connfd = accept( fd, ( struct sockaddr* )&sin, &len );
30     if ( connfd == -1 )
31     {
32         perror( "accept" );
33     }
34     else
35     {
36         fprintf( stdout, "peer address ------ [%s:%d]\n", inet_ntoa( sin.sin_addr ), ntohs( sin.sin_port ) );
37     }
38 
39     return connfd;
40 }

 

posted on 2016-04-10 00:15  郁郁思扬  阅读(748)  评论(0编辑  收藏  举报

导航