我正在使用Pthread在C中使用多线程服务器应用程序。如果客户端发送关闭连接的请求,我可以退出线程并释放它使用的资源。我正在粘贴下面的代码
MAIN.C
#include "extern.h"
int thread_counter = 0;
int rc;
void main(int argc, char** argv){
int sock_desc = 0, connfd = 0;
struct sockaddr_in serv_addr;
int clntSock;
struct sockaddr_in echoClntAddr;
int n = 0;
pthread_t thr;
sock_desc = socket(AF_INET, SOCK_STREAM, 0);
if(sock_desc < 0 )
dieWithError("Unable to open Socket\n");
fcntl(sock_desc, F_SETFL, fcntl(sock_desc, F_GETFL, 0) | O_NONBLOCK);
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET ;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(7024);
if(bind(sock_desc, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
dieWithError("bind failed\n");
if(listen(sock_desc,MAX_CONNECTIONS) < 0)
dieWithError("listen failed\n");
clntSock = sizeof(struct sockaddr);
int i =0;
while(1){
connfd = accept(sock_desc, (struct sockaddr *)&echoClntAddr,(socklen_t*)&clntSock);
if(connfd > 0){
puts("Connection accepted");
if(pthread_create( &thr, NULL , connection_handler , (void*)connfd) < 0){
perror("could not create thread");
}
puts("Handler assigned");
}
}
}
void dieWithError(char *errormsg){
printf("%s", errormsg);
}
HandleConnection.C
#include "extern.h"
void *connection_handler(void *socket_desc){
int sock = (int) socket_desc;
int read_size;
char client_message[2000];
int i;
int rc = 5;
while(1){
read_size = recv(sock , client_message , 2000 , 0);
if(read_size > 0){
client_message[read_size] = '\0';
printf("%s",client_message);
}
memset(client_message, 0, 2000);
if(read_size == 0){
puts("Client disconnected");
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);
fflush(stdout);
rc = close(sock);
break;
}
else if(read_size == -1){
perror("received failed");
break;
}
}
}
如何以及在何处编写例程以在其工作结束后退出线程。我尝试使用pthreads_cancel,但它没有帮助,理由可能是我没有正确使用它。