Hi all, I've written a readn() functions like the Stevens' well-known one which also specifies a timeout via the select() function:
Code:
int readn (int sockfd, void *buff, size_t n, int timeo){
int n_left;
int n_read;
char *ptr;
ptr = buff;
n_left = n;
struct timeval timeout;
fd_set fds;
timeout.tv_sec = timeo;
timeout.tv_usec = 0;
FD_ZERO(&fds);
FD_SET(sockfd, &fds);
while(n_left>0){
if (select(sockfd+1, &fds, 0, 0, &timeout)>0){
if((n_read=read(sockfd,ptr,n_left))<0){
if(errno == EINTR)
n_read=0;
else{
return -1;
}
}
else if(n_read==0){
printf("n_read=0\n");
break;
}
n_left-=n_read;
printf("%s\n", ptr);
ptr+=n_read;
}
else{
return -1;
}
}
return (n-n_left);
}
When i call readn() in my main()
Code:
readn(sockfd,buffer,MAXLINE, 5)
I notice that the inner read() function doesn't return 0 when it reaches EOF (I notice that it has finished reading by printing ptr), but waits the timeout specified by select(). If I don't specify a timeout at all, read() holds forever.
On the other side, if in my main() I call the simple read() function instead of readn(),
Code:
read(sockfd,buffer,MAXLINE)
it returns 0, working as intended.
I really can't figure out what the problem may be, since what I see is that the same read() call works as it should outside readn(), and holds until interrupted inside readn(). Thanks for your patience,
Regards, Stefano