linuxer_lhw
全部博文(17)
linux编程工具(0)
linux应用编程(0)
GUI(0)
2009年(17)
yqy_work
yangyefe
NIHAO111
liao4155
alqaida
gj198909
totopper
分类: C/C++
2009-11-04 20:07:54
#include "apue.h" ssize_t readn(int fd, void *ptr, size_t n) { size_t nleft; ssize_t nread; nleft = n; while (nleft > 0) { if ((nread = read(fd, ptr, nleft)) < 0) { //当read返回-1, if (nleft == n) return(-1); /*若第一次read时出错, readn 返回 -1 */ else break; /*若读了一些数据后出错, readn返回已经读的字节数,而不出错返回 */ } else if (nread == 0) { //当read返回0时,不再读下去,readn返回已经读的字节数 break; /* EOF */ } nleft -= nread; //当read返回值>0但不等于n时,继续读 ptr += nread; } return(n - nleft); /* return >= 0 */ } ssize_t writen(int fd, const void *ptr, size_t n) size_t nleft; ssize_t nwritten; nleft = n; while (nleft 0) { if ((nwritten = write(fd, ptr, nleft)) < 0) { //当write返回-1, if (nleft == n) /*若第一次write时出错, writen 返回 -1 */ return(-1); else break; /*若写了一些数据后出错, writen返回已经读的字节数,而不出错返回 */ } else if (nwritten == 0) { //当write返回0时,不再写下去,writen返回已经读的字节数 break; } nleft -= nwritten; //当write返回值>0但不等于n时,继续写 ptr += nwritten; } return(n - nleft); /* return >= 0 */ }
#include "unp.h" ssize_t 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) { //当read返回-1, if (errno == EINTR) nread = 0; /*若出错是因为被信号中断,继续读*/ else return(-1); //若不是因为被信号中断而出错,则不再读readn返回-1 } else if (nread == 0) //当read返回0时,不再读下去,readn返回已经读的字节数 break; /* EOF */ nleft -= nread; //当read返回值>0但不等于n时,继续读 ptr += nread; } return(n - nleft); /* return >= 0 */ } ssize_t 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) { //当write出错返回-1或者返回0时, if (nwritten < 0 && errno == EINTR) nwritten = 0; /*若出错返回-1是因为被信号中断,继续写 */ else return(-1); //若不是因为被信号中断而出错返回-1或者 返回0时,则不再写writen返回-1 } nleft -= nwritten; //当write返回值>0但不等于n时,继续写 ptr += nwritten; } return(n); }
again: while ( (n = read(sockfd, buf, MAXLINE)) > 0) //调用read writen(sockfd, buf, n); //调用writen if (n < 0 && errno == EINTR) goto again; else if (n < 0) err_sys("str_echo: read error"); }
上一篇:非阻塞IO
下一篇:linux中的定时
登录 注册