0

私は現在、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 );
4

1 に答える 1

1

いいえ、それはできません。子スレッドからソケットを閉じる関数を呼び出すことをお勧めします。を使用しpthread_mutexて、一度に1つのスレッドからのみ実行していることを確認します。また、では、ソケットが適切に閉じられたために発生したmainエラーを処理します。tcp_wait_for_connection

于 2012-06-06T18:48:05.260 に答える