我目前正在用 C 编写一个基本客户端服务器消息传递程序。我遇到的问题是服务器端代码。代码的主要部分是一个 while 循环,用于检查来自客户端的新传入套接字连接。如果客户端连接,则会产生一个新线程来处理传入消息。我使用的这个功能tcp_wait_for_connection( server );
是阻塞的。
所以我的问题是是否可以从这些线程之一中断while循环而不必使用 Exit() 以便我可以关闭套接字
(我是 Stack Overflow 的新手,所以我不知道是否应该在此处发布我的完整代码,我将最相关的部分放在下面,如果您需要更多我会编辑帖子。
谢谢
代码如下:
while(1) {
client = (Socket *) malloc( sizeof(Socket) ); //allocate memory for the new client socket
if ( client == NULL ){
perror("Allocation of memory for the new client has failed");
return 1;
}
//wait for a client to connect
*client = tcp_wait_for_connection( server );
printf("Incoming client connection\n");
//get the socket descriptor for the new client socket
sd = get_socket_descriptor(client);
//insert the new client socket into the client list with the sd as ID
InsertElement(&cl, (Element)client, sd);
p_thread = (pthread_t *) malloc( sizeof(pthread_t) ); //allocate memory for the new thread handler
if ( p_thread == NULL ){
perror("Allocation of memory for the new thread has failed");
return 1;
}
//insert the new thread handler into the thread handler list
//with the sd of the corressponding client socket as ID
InsertElement(&tl, (Element)p_thread, sd);
//create the new thread
pthread_create(p_thread, NULL, HandleClient, (void*)p_thread);
}
tcp_close( *client );
tcp_close( server );