I have the sample code from chapter 16.2 of Sockets book by Richard Stevens which is an asynchronous client that reads/writes into sockets/stdin/stdout. The simplified version is below. Now I need to enhance this code so it will send
a heartbeat to a server if there was not any communication with the server for 60 seconds. Currently this code hangs indefinitely at select() untill the data appear at the socket or stdin.
I'll appriciate any suggestions how I can add the heartbeat functionality. I am running Ubuntu.
for ( ; ; )
{
int ret = select(maxfdp1, &rset, &wset, NULL, &timeout);
if( ret == 0) // timed out
{
// HEARTBEAT FUNCTIONALITY HERE;
}
// read from stdin.
if ( FD_ISSET(STDIN_FILENO, &rset) )
n = read(STDIN_FILENO, toiptr, &to[MAXLINE] - toiptr));
// read from socket.
if ( FD_ISSET(sockfd, &rset) )
n = read(sockfd, friptr, &fr[MAXLINE] - friptr);
// write to stdout.
if (FD_ISSET(STDOUT_FILENO, &wset) )
nwritten = write(STDOUT_FILENO, froptr, n);
// write to socket.
if (FD_ISSET(sockfd, &wset) )
nwritten = write(sockfd, tooptr, n);
} // for ( ; ; )
It waits 5 seconds but only on the first iteration of the loop, on subsequent iterations select() does not wait at all, it just goes right through. I expected it to wait every time.
Could someone help me with this so select() times out every time?