私は現在、Cで基本的なクライアントサーバーメッセージングプログラムをプログラミングしています。私が抱えている問題は、サーバー側のコードにあります。コードの主要部分は、クライアントからの新しい着信ソケット接続をチェックするwhileループです。クライアントが接続すると、着信メッセージを処理する新しいスレッドが生成されます。私が使用するこの関数tcp_wait_for_connection( server );
はブロッキングです。
だから私の質問は、Exit()を使用せずにこれらのスレッドの1つからwhileループを壊して、ソケットを閉じることができるかどうかです。
(私はStackオーバーフローに慣れていないので、ここに完全なコードを投稿する必要があるかどうかわかりませんでした。最も関連性の高い部分を下に配置しました。さらに必要な場合は、投稿を編集します。
ありがとう
コードは次のようになります。
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 );