轉自:http://blog.csdn.net/yanook/article/details/6587542
socket上的read write 操作不同與一般的檔案IO操作,socket上的用read write讀寫的位元組數可能比要求的少,但這並不是錯誤,原因是socket的緩衝區可能已經達到了極限。此時所需要的就是再次調用read write 以寫入或輸出剩餘的字元。這種情況在socket中很常見,但在寫位元組流socket時只能在socket非堵塞的情況下才會出現,然而為預防實現萬一返回不足的字元數值,我們總是調用writen和readn函數,而不是read和write.
下面就是readn、writen函數源碼:
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);
}