Note that there are some explanatory texts on larger screens.

plurals
  1. POblocking select() from multiple sockets
    primarykey
    data
    text
    <p>Unix/C question here. </p> <p>I have multiple sockets that I am trying to poll for periodic data. I don't want select to wait indefinitely so I have a timeout in place and I'm running in a loop. I have found that once a socket is ready to read, <strong>it is always ready to read</strong>. As in, I cannot have select go to sleep when there is no data to be read from any of the sockets. </p> <pre><code>for (i = 0; i &lt; n_connections; i++) { FD_SET( sockfd[i], &amp;master ); if (sockfd[i] &gt; fdmax) fdmax = sockfd[i]; } for(;;) { int nready = 0; timeout.tv_sec = 1; timeout.tv_usec = 0; read_fds = master; if ( (nready = select(fdmax+1, &amp;read_fds, NULL, NULL, NULL)) == -1 ) { fprintf( stderr, "Select Error\n" ); return FAILURE; } printf( "Number of ready descriptors: %d\n", nready ); for (i = 0; i &lt;= fdmax; i++) { if (FD_ISSET(i, &amp;read_fds)) { if (( nbytes = recv(i, buf, sizeof(buf), 0)) &lt;= 0 ) { if (nbytes == 0) { //connection closed printf("Socket %d hung up\n", i ); } else { fprintf( stderr, "Recv Error %d\n", nbytes); } } else { printf( "Data Received on %d: %s\n", i, buf ); } } } // end file descriptor loop </code></pre> <p>It seems that after my first read, the 1 second timeout no longer applies and the socket is always "ready to read", even if there are 0 bytes available. How can I get select to sleep until data comes in (for the one second, or by switching the final argument to NULL, indefinitely waiting for data to come in on the socket?)</p> <p>Output: </p> <pre><code>Number of Ready Descriptors: 2 Data Received on 4: GreetingsChap Data Received on 5: HiMatengsChap Loop... Number of Ready Descriptors: 2 Socket 4 hung up Socket 5 hung up Loop... Number of Ready Descriptors: 2 Socket 4 hung up Socket 5 hung up Loop... </code></pre> <p>Thank you,</p> <p>Note: Code updated for clarity Updated based on @yvesBraumes suggestions - still doesn't work.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload