2012-06-06 46 views
0

我目前正在用C語言編寫基本客戶端服務器消息程序。 我遇到的問題是服務器端代碼。 代碼的主要部分是一個while循環,用於檢查來自客戶端的新傳入套接字連接。 如果客戶端連接,會產生一個處理傳入消息的新線程。這個函數我使用tcp_wait_for_connection(server);是阻塞的。從主線斷開while循環。 (C編程)

所以我的問題是,如果有可能突破從某個線程的while循環,而不必使用退出()這樣我就可以關閉套接字

(我是新來的堆棧溢出,從而我不知道我是否應該張貼在這裏還是不是我完整的代碼,我把最相關的部分如下,如果你需要更多的,我會編輯的帖子

感謝

的代碼是這樣的:

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); 
+0

我不太記得C,但我想你可以使用break ;. (我不確定) –

+0

你問你是否可以使用'break'來使_break_脫離循環? –

+0

@ K-ballo他是否可以從一個產生的線程中'破壞'。 –

回答

1

不,你不能那樣做。我建議你只是調用關閉子線程中的套接字的函數。使用pthread_mutex來確保您一次只能從一個線程執行此操作。此外,在main中,處理由於套接字已正確關閉而發生的tcp_wait_for_connection錯誤。