socket problem?

Kartik Subbarao subbarao at phoenix.Princeton.EDU
Wed May 22 00:25:39 AEST 1991


In article <1991May20.210923.12177 at rfengr.com> brian at coconut.com writes:
>
>Question about sockets.  I've got a simple server program that runs in the
>background.  It sits in an infinite loop, with an accept() call, waiting

>It's the client side that's got a bug.  It sets up its socket with
>the server successfully, connect()'s successfully, etc.  Sends out 
>its 'r' successfully (cuz the server gets it and sends out its struct)
>but the client's read() never works.  The client has a read() function
>such as this
>
>	read( sd, &theStruct, sizeof(theStruct) );
>
>where sd is the socket descriptor and theStruct is just some big structure.
>Read returns a value of 3 or it just blocks altogether.  Any ideas?

This is not a "bug", but rather a documented feature of sockets. reads and
writes are not guaranteed to transfer exactly the amount of data that you
request to be sent. Therefore, in doing I/O on sockets, its safer to make
sread() and swrite() functions that read until either all the requested
data is read/written, or -1 or 0 is returned. Here's what I use:

int sread(int s, char *buf, int n)
{
	int save = n;
	int tmp; /* number of chars read this call */
	while (n) {
		if ((tmp = read(s, buf, n)) <= 0)
			return tmp ? tmp : save-n; 
		n -= tmp; buf += tmp;
    }
    return save;
}

swrite() is exactly the same thing, replace the read(...) with write(...);

		-Kartik

--
internet% ypwhich

subbarao at phoenix.Princeton.EDU -| Internet
kartik at silvertone.Princeton.EDU (NeXT mail)  
SUBBARAO at PUCC.BITNET			          - Bitnet



More information about the Comp.unix.wizards mailing list