c - How to cleanly interrupt a thread blocking on a recv call? -
i have multithreaded server written in c, each client thread looking this:
ssize_t n; struct request request; // main loop: receive requests client , send responses. while(running && (n = recv(sockfd, &request, sizeof(request), 0)) == sizeof(request)) { // process request , send response. } if(n == -1) perror("error receiving request client"); else if(n != sizeof(act)) fprintf(stderr, "error receiving request client: incomplete data\n"); // clean-up code.
at point, client meets criteria must disconnected. if client regularly sending requests, fine because can informed of disconnection in responses; clients take long time send request, client threads end blocking in recv
call, , client not disconnected until next request/response.
is there clean way disconnect client thread while client thread blocking in recv
call? tried close(sockfd)
causes error error receiving request client: bad file descriptor
occur, isn't accurate.
alternatively, there better way me handling errors here?
so have @ least these possibilities:
(1) pthread_kill
blow thread out of recv
errno == eintr , can clean , exit thread on own. people think nasty. depends, really.
(2) make client socket(s) non-blocking , use select
wait on input specific period of time before checking if switch used between threads has been set indicated should shut down.
(3) in combo (2) have each thread share pipe master thread. add select
. if becomes readable , contains shutdonw request, thread shuts down.
(4) pthread_cancel
mechanism if none of above (or variations thereof) not meet needs.
Comments
Post a Comment