View Full Version : How to check if data come in from the socket without hanging there!!!
KingdomHeart
2007.11.22, 04:22 PM
How do I check if there is data coming in from the socket without hang on to that socket.
Right now this is what I have
if(read(sockfd, recvline, MAXLINE)){
//processs.
//Code hang here until something come in from the socket. DONT WANT THIS
}
Here is what I want to happen but dont know how to do it
if(data coming in){
//process
}else{
//move on
}
Cochrane
2007.11.23, 01:28 AM
With select(2). Basic case for just one socket (read the manpage for full information):
fd_set sockset;
FD_ZERO(&sockset);
FD_SET(your_socket_here, &sockset);
int result = select(your_socket_here + 1, sockset, NULL, NULL, NULL);
if (result < 0)
{
// You have an error
}
else if (result == 1)
{
// The socket has data. For good measure, it's not a bad idea to test further
if (FD_ISSET(your_socket_here, &sockset)
{
// Process
}
}
else
{
// Move on
}
That looks like a lot of code for such a basic task (and in fact, it is), but select can also tell you if one of many socket has something to say, as well as lots of other stuff.
KittyMac
2007.11.23, 11:25 AM
You can also flag it as non-blocking by using fcntl
fcntl(fileDescriptor,
F_SETFL,
O_NONBLOCK);
vBulletin® v3.6.8, Copyright ©2000-2008, Jelsoft Enterprises Ltd.