一、第一版
#include <unistd.h>
#include <errno.h>
ssize_t readline(int fd, void *vptr, size_t maxlen) {
ssize_t n, rc;
char c, *ptr;
ptr = vptr;
for (n = 1; n <= maxlen; n++) {
again:
if ( (rc = read(fd, &c, 1)) == 1) {
*ptr++ = c;
if (c == '
') {
break;
}
} else if (rc == 0) {
*ptr = 0;
return (n - 1);
} else {
if (errno == EINTR) {
goto again;
}
return (-1);
}
}
*ptr = 0;
return ((maxlen == (n-1))?(n-1):n);
}
函数功能:从一个描述符读文本行,一次一个字节
二、改进版
#include <errno.h>
#include <unistd.h>
#define MAXLINE 4096
static int read_cnt = 0;
static char *read_ptr;
static char read_buf[MAXLINE];
static ssize_t my_read(int fd, char *ptr) {
if (read_cnt <= 0) {
again:
if ( (read_cnt = read(fd, read_buf, sizeof(read_buf))) < 0) {
if (errno == EINTR) {
goto again;
}
return (-1);
} else if (read_cnt == 0) {
return (0);
}
read_ptr = read_buf;
}
read_cnt--;
*ptr = *read_ptr++;
return (1);
}
ssize_t readline(int fd, void *vptr, size_t maxlen) {
ssize_t n, rc;
char c, *ptr;
ptr = vptr;
for (n = 1; n < maxlen; n++) {
if ( (rc = my_read(fd, &c)) == 1) {
*ptr++ = c;
if (c == '
') {
break;
}
} else if (c == 0) {
*ptr = 0;
return (n - 1);
} else {
return (-1);
}
}
*ptr = 0;
return (n);
}
ssize_t readlinebuf(void **vptrptr) {
if (read_cnt) {
*vptrptr = read_ptr;
}
return (read_cnt);
}
功能:readline的改进版,自带缓冲区
问题:使用静态变量实现跨域相继函数调用的状态信息维护,使函数变得不可重入或者说非线程安全