• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 235
  • Last Modified:

read()

Hi there i'm working with a mail client in linux.
My problem is : when i use the func read to read from the socket it prompts until data arrives so if
no data arrives it just prompts forever. I wonder if there is a possibility to abort it after sometime or with another function??
0
marcoo
Asked:
marcoo
  • 2
  • 2
1 Solution
 
yowkeeCommented:
To deal with socket, you'd rather use send() and recv() instead of write() and read(), to gain greater control over data transmission. For a guide for start, take a look at http://www.ecst.csuchico.edu/~beej/guide/net/
0
 
vvijaykCommented:
Use the select system call. It allows you to specify for what time you want to monitor a number of file descriptors. It is very good for monitoring a no. of fds, including sockets, at the same time.
       Specify your socket fd as the one to monitor for reading in select() alongwith the timeout. When the select call returns, check its reason for return i.e. data has arrived or timeout occurred. U can then read data from socket accordingly.
0
 
marcooAuthor Commented:
Ehh.. i don't quite understand do you think you can give me an example??
I'd appreciate it Marcoo..
0
 
vvijaykCommented:
Here's the example :
Suppose ur socket fd is sockfd.

fd_set rfds;
struct timeval tv;
int retval;

FD_ZERO(&rfds);
FD_SET(sockfd,&rfds);  /*Set sockfd for read monitoring*/

/*Set wait time to say 5 sec*/
tv.tv_sec = 5; /*Seconds*/
tv.tv_usec = 0; /*Milliseconds*/

retval = select(1,&rfds,NULL,NULL,&tv);

/*At this point the select call will block waiting for either some data to appear in sockfd or timeout to expire*/

if(retval)
{
 /*Check if select call has returned due to data in sockfd*/
if(FD_ISSET(sockfd,&rfds))
 {/*Process sockfd data*/}
}
else {/*No data within 5 seconds*/}

I hope its clear now.
0
 
marcooAuthor Commented:
OK thanx i'll will try it out..
0

Featured Post

SMB Security Just Got a Layer Stronger

WatchGuard acquires Percipient Networks to extend protection to the DNS layer, further increasing the value of Total Security Suite.  Learn more about what this means for you and how you can improve your security with WatchGuard today!

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now