int my_read(int fd, void *buffer, int length)
{
int bytes_left;
int bytes_read;
char *ptr = NULL;
bytes_left = length;
while (bytes_left > 0)
{
bytes_read = read(fd, ptr, bytes_read);
if (bytes_read < 0)
{
if (errno == EINTR)
{
bytes_read = 0;
}
else
{
return(-1);
}
}
else if (0 == bytes_read)
{
break;
}
bytes_left -= bytes_read;
ptr += bytes_read;
}
return(length-bytes_left);
}
这个只能针对阻塞模式的socket设置read超时,在setsocket函数里面设置read和write的超时时间;非阻塞模式的socket需要处理EAGAIN错误。
http://blog.sina.com.cn/s/blog_5acb430f0100aer1.html