I have a multithreaded server written in C, with each client stream looking something like this:
ssize_t n; struct request request; // Main loop: receive requests from the client and send responses. while(running && (n = recv(sockfd, &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.
At some point, the client meets certain criteria where it should be disconnected. If the client regularly sends requests, this is normal, because it may be informed that responses are disabled; However, sometimes clients take a long time to send a request, so client flows are blocked in the recv call, and the client does not disconnect until the next request / response.
Is there a clean way to disconnect a client from another thread while the client thread is blocking in a recv call? I tried close(sockfd) , but this caused an Error receiving request from client: Bad file descriptor error, which is really inaccurate.
Alternatively, is there a better way for me to handle errors here?
source share