title: How to cleanly interrupt a thread blocking on a recv call?
body: <p>I have a multithreaded server written in C, with each client thread looking something like this:</p>
  
  <pre><code>ssize_t n;
  struct request request;
  
  // Main loop: receive requests from the client and send responses.
  while(running &amp;&amp; (n = recv(sockfd, &amp;request, sizeof(request), 0)) == sizeof(request)) {
      // Process request and send response.
  }
  if(n == -1)
      perror("Error receiving request from client");
  else if(n != sizeof(act))
      fprintf(stderr, "Error receiving request from client: Incomplete data\n");
  
  // Clean-up code.
  </code></pre>
  
  <p>At some point, a client meets a certain criteria where it must be disconnected. If the client is regularly sending requests, this is fine because it can be informed of the disconnection in the responses; However sometimes the clients take a long time to send a request, so the client threads end up blocking in the <code>recv</code> call, and the client does not get disconnected until the next request/response.</p>
  
  <p>Is there a clean way to disconnect the client from another thread while the client thread is blocking in the <code>recv</code> call? I tried <code>close(sockfd)</code> but that causes the error <code>Error receiving request from client: Bad file descriptor</code> to occur, which really isn't accurate.</p>
  
  <p>Alternatively, is there a better way for me to be handling errors here?</p>