[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

15. Pitfalls

Deadlocks in datagram sockets are the most common mistakes that novices make. To alleviate the problem, sockbuf class provides timeout facilities that can be used effectively to avoid deadlocks.

Consider the following simple tsmtp example which sends the HELP command to a smtp server and gets back the help message. Suppose it does not know the size of the help message nor the format of the message. In such cases, the timeout facilities of sockbuf class provides the required tools.

The example terminates the help message reception if the there is no input activity from the smtp server for 10 seconds.

tsmtp.cc

 
#include <sockinet.h>

int main()
{
	iosockinet   sio(sockbuf::sock_stream);

	sio->connect("kelvin.seas.virginia.edu", "smtp", "tcp");

	char buf[512];
	sio.getline(buf, 511); cout << buf << endl;
	sio << "HELO kelvin\n" << flush;
	sio.getline(buf, 511); cout << buf << endl;

	sio << "HELP\n" << flush;

        // set the receive timeout to 10 seconds
        int tmo = sio->recvtimeout(10);

	while ( sio.getline(buf, 511) ) cout << buf << endl;
		// if the above while loop terminated due to timeout
		// clear the state of sio.
	if ( !sio->is_eof() )
		sio.clear();  
	sio->recvtimeout(tmo); // reset the receive timeout time

	sio << "QUIT\n" << flush;
	sio.getline(buf, 511); cout << buf << endl;
        return 0;
}


[ << ] [ >> ]           [Top] [Contents] [Index] [ ? ]

This document was generated by Herbert Straub on June, 15 2005 using texi2html