Question

I wrote an update function that is called from the main loop. Since the implementation is subjected to certain timing constraints it is programmed in such way that each update function is aloud to take 50 ms max. In the case a function does not return a value within 50 ms the main loop aborts with an error message stating that a certain function took to long.

The issue is that I am trying to read from a earlier setup (opened) socket. Sometimes reading from this socket takes 10 ms, but in other cases it takes 100 ms allowing the main loop to abort. Therefore, it seems to be the case that I wrote this function using blocking methods. I have no idea how I can solve this or even implement a solution to this. Someone gave me the hint to work with a timer. The function is:

int socket_update(void) {
    n = read(sockfd, recvBuff, sizeof(recvBuff)-1);
    if (n > 0) {
       //Run some code    
    } else if (n < 0) {
       printf("\n Read error \n");
       return 0;
   }
   return 1;
}

Therefore, I am under the impression that the read function is blocking the main loop.

How can I solve this?

Was it helpful?

Solution

You can either:

  1. Set the socket into non-blocking mode, with ioctl() and the F_NBIO flag, in which case read() will return -1 with errno set to EWOULDBLOCK/EAGAIN if there is no data, or, more probably

  2. Set a read timeout, with setsockopt() and the SO_RCVTIMEO option.

NB your current code is flawed in that it doesn't handle end of stream (read() returns zero) at all, and in that treats all read() errors alike. They aren't. Some, such as ECONNRESET, are fatal to the connection and should cause its closure.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top