Turn from: http://blog.csdn.net/yanook/article/details/6587542
The read write operation on the socket differs from the normal file IO operation, and the number of bytes read write on the socket may be less than required, but this is not an error because the socket buffer may have reached its limit. All that is needed is to call read Write again to write or output the remaining characters. This is common in sockets, but occurs only when the socket is not plugged in while writing a throttle socket, but we always invoke the writen and READN functions instead of read and write for the purposes of prevention, in case of returning insufficient character values.
The following is the READN, writen function Source:
ssize_t/* Read "n" bytes from a descriptor. */
READN (int fd, void *vptr, size_t N)
{
size_t Nleft;
ssize_t nread;
Char *ptr;
ptr = vptr;
Nleft = n;
while (Nleft > 0) {
if ((nread = Read (FD, PTR, nleft)) < 0) {
if (errno = = eintr)
nread = 0; /* and call Read () again * *
Else
Return (-1);
else if (nread = 0)
Break /* EOF * *
Nleft-= nread;
PTR + = nread;
}
return (N-nleft); /* Return >= 0 * *
}
ssize_t/* Write "n" bytes to a descriptor. */
writen (int fd, const void *vptr, size_t N)
{
size_t Nleft;
ssize_t Nwritten;
const char *ptr;
ptr = vptr;
Nleft = n;
while (Nleft > 0) {
if ((Nwritten = write (FD, PTR, nleft)) <= 0) {
if (Nwritten < 0 && errno = = eintr)
Nwritten = 0; /* and call Write () again * *
Else
Return (-1); /* ERROR * *
}
Nleft-= Nwritten;
PTR + = Nwritten;
}
return (n);
}