0

I want to build a while loop that continuously reads from a non-blocking socket whether or there are message sent. I use the read function to read from the socket but when ever it gets to read(), the while loop is blocked. Do I also need to make read non-blocking?

while(1){

  char client_response[256];
  client_response = (char*) malloc(256);

  int reader = read(socket_fd, server_response, sizeof(server_response));
  printf("passed reader\n");   // this never shows
  if(reader < 0){
     perror("read fails\n");
     return -1;
  }
  sleep(1);
}
NNNNNNN
  • 83
  • 4
  • Did you do a search? For example: Does [this](https://stackoverflow.com/questions/5616092/non-blocking-call-for-reading-descriptor) or [this](https://stackoverflow.com/questions/1525050/non-blocking-socket) help? – kaylum Dec 07 '19 at 04:13
  • Which Operating System? It makes a difference. – selbie Dec 07 '19 at 06:27
  • I found it hard to believe that your assignment of the pointer returned from `malloc` to a fixed size array doesn't result in a compile error. – selbie Dec 07 '19 at 06:35
  • Can you show us the code that sets the socket non-blocking? – David Schwartz Dec 07 '19 at 06:35

1 Answers1

0

I'm not certain how you are configuring your socket for non-blocking. But the steps are different between Windows and Unix. If you can tell me the OS, I can give more details on non-blocking socket configuration.

Below is a more platform neutral way to poll a socket in a non-blocking way without having explicitly configured the socket for non-blocking. Either use the MSG_DONTWAIT flag (if available) or the MSG_PEEK flag as hint to see if the call can be made.

Also, let's just use recv instead of read since this is a socket.

 #ifdef MSG_DONTWAIT
    int reader = recv(socket_fd, server_response, sizeof(server_response), MSG_DONTWAIT);
#else
    int reader = recv(socket_fd, server_response, sizeof(server_response), MSG_PEEK);
    if (reader > 0)
    {
        reader = recv(socket_fd, server_response, sizeof(server_response), 0);
    }
#endif
selbie
  • 91,215
  • 14
  • 97
  • 163