How to check if data come in from the socket without hanging there!!!

KingdomHeart
Unregistered
 
Post: #1
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
Code:
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

Code:
if(data coming in){
    //process
}else{
    //move on
}
Quote this message in a reply
Member
Posts: 114
Joined: 2005.03
Post: #2
With select(2). Basic case for just one socket (read the manpage for full information):
Code:
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.
Quote this message in a reply
Member
Posts: 204
Joined: 2002.09
Post: #3
You can also flag it as non-blocking by using fcntl

Code:
fcntl(fileDescriptor,
        F_SETFL,
        O_NONBLOCK);
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Socket Library on OSX? MacFiend 16 12,472 Apr 15, 2010 05:44 AM
Last Post: Kirienko
  App hanging and crash log. Najdorf 3 3,286 Oct 27, 2008 07:46 AM
Last Post: Najdorf
  OpenGL + Socket!!! Flush socket problem!!! KingdomHeart 4 4,869 Nov 21, 2007 10:14 AM
Last Post: Zekaric
  BSD Socket: Send Data but never Receive kodex 2 8,048 Jul 1, 2005 10:56 PM
Last Post: kodex
  Cocoa Socket Control? SummerLand 4 5,567 Dec 1, 2002 01:52 AM
Last Post: Gastropod