字节流套接字上调用read、write输入或输出的字节数可能比请求的数量少,然而这不是出错的状态。这个现象的原因在于内核中用于套接字的缓冲区可能已达到了极限。此时需要再次调用read或write函数,以输入或输出剩余的字节。
以下三个函数就是用于此目的:
-
#include <unistd.h>
-
#include <signal.h>
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <errno.h>
-
#include "readn.h"
-
-
int readn(int fd, void* buffer, size_t n)
-
{
-
int nread;
-
int nleft;
-
char *ptr;
-
-
ptr = buffer;
-
nleft = n;
-
while(nleft >0) {
-
if((nread=read(fd,ptr,nleft)) < 0){
-
if(errno == EINTR) {
-
nread = 0;
-
continue;
-
}else {
-
return -1;
-
}
-
}else if (nread==0) {
-
break;
-
}
-
ptr += nread;
-
nleft -= nread;
-
}
-
return (n - nleft);
-
}
-
-
int writen(int fd, void* buffer, size_t n)
-
{
-
int nwrite;
-
int nleft;
-
char* ptr;
-
-
ptr = buffer;
-
nleft = n;
-
while(nleft > 0) {
-
if((nwrite = write(fd,ptr,nleft)) < 0) {
-
if(errno == EINTR) {
-
nwrite = 0;
-
continue;
-
}else {
-
return -1;
-
}
-
}else if(nwrite == 0){
-
break;
-
}
-
ptr += nwrite;
-
nleft -= nwrite;
-
}
-
return (n-nleft);
-
}
-
-
size_t readline(int fd, void * buffer, size_t maxlen)
-
{
-
int i;
-
int nread;
-
char c;
-
char *ptr;
-
-
ptr=buffer;
-
for(i = 0;i < maxlen;i++) {
-
again:
-
if((nread = read(fd,&c,1)) == 1){
-
*ptr++ = c;
-
if(c == '\n')
-
break;
-
}else if(nread == 0) {
-
*ptr = 0;
-
return i-1;
-
}else {
-
if(errno == EINTR) {
-
goto again;
-
}else {
-
return -1;
-
}
-
}
-
}
-
*ptr = 0;
-
return i;
-
}
-
static char *ptr;
-
static int len = 0;
-
char read_buffer[MAXLINE];
-
ssize_t my_read(int fd, char* buffer)
-
{
-
int nread;
-
-
if(len <= 0) {
-
again:
-
if((nread = read(fd,read_buffer,MAXLINE)) < 0) {
-
if(errno == EINTR)
-
goto again;
-
return -1;
-
}else if(nread == 0) {
-
return 0;
-
}
-
ptr = read_buffer;
-
len = nread;
-
}
-
*buffer = *ptr++;
-
len--;
-
return 1;
-
}
阅读(856) | 评论(0) | 转发(0) |