-1

I am using infinite while loop to receive data from TCP server I need to perform other task in loop simultaneously having higher priority But control holds to recv() function every time it waits for TCP data.

while(1)
{
        rdlen = read(fd1, buf, (sizeof(buf) - 1));
        if (rdlen > 0) 
        {
            buf[rdlen] = 0;
            printf("%s",buf);
            memset(buf, 0, strlen(buf));
        }
        if((numbytes=recv(sockfd, buf1, wGetLen, 0)) != -1)
        {
            printf("%s %d\n", buf1, numbytes);
            memset(buf1, 0, strlen(buf1));                                
        }
}

How can I perform above operation without waiting for TCP to receive data?

dlmeetei
  • 9,905
  • 3
  • 31
  • 38
Sanket
  • 1
  • 1
  • 1
    https://stackoverflow.com/questions/15108122/recv-with-non-blocking-socket – Retired Ninja Sep 06 '17 at 13:17
  • 3
    Put the socket in non-blocking mode, and / or use `select()`, `poll()`, or similar to determine whether there is data available before you try to read from the socket. – John Bollinger Sep 06 '17 at 13:20
  • 2
    Cargo-cult programming : `memset(buf1, 0, strlen(buf1));` This is dangerous nonsense, IMHO – wildplasser Sep 06 '17 at 13:27
  • ^^^ what @wildplasser says. At best, such 'clear the buffer' operations are a waste of cycles, at worst, disastrous. If strlen() is involved anywhere, then the scales tip heavily towards the dark side:( – Martin James Sep 06 '17 at 14:00
  • 1
    Thread off the recv() loop? – Martin James Sep 06 '17 at 14:01
  • Possible duplicate of [recv with non-blocking socket](https://stackoverflow.com/questions/15108122/recv-with-non-blocking-socket) – dlmeetei Sep 06 '17 at 15:25

1 Answers1

2

You need to set up the socket as a non-blocking socket. In doing so, if you call recv and there is nothing to be received, the function call will return -1 to indicate an error with EAGAIN as the error code.

You can set the non-blocking flag as follows

int fdflag;
if ((fdflag = fcntl(sockfd, F_GETFL)) == -1) {
    perror("Error getting socket descriptor flags");
    exit(1);
}
fdflag |= O_NONBLOCK;
if (fcntl(sockfd, F_SETFL, fdflag) == -1) {
    perror("Error setting non-blocking option");
    exit(1);
}

Then you can change your recv call as follows:

     if((numbytes=recv(sockfd, buf1, wGetLen, 0)) != -1)
     {
         printf("%s %d\n",buf1,numbytes);
         memset(buf1, 0, sizeof(buf1));                                
     }
     else if (errno == EAGAIN)
     {
         printf("no data to receive\n");
     }
     else
     {
         perror("error on recv");
     }    
dbush
  • 205,898
  • 23
  • 218
  • 273
  • Yes using above able to do other operation simultaneously but if data is available to recieve. " buf1" is showing empty. – Sanket Sep 07 '17 at 06:22