我已經使用pthread庫在c中編寫了多客戶端服務器。當每個客戶端嘗試連接到服務器時,每個客戶端都作爲單獨的線程運行,並使用handle_client函數處理每個客戶端。爲什麼線程函數的參數應該在堆中?
我想知道爲什麼我需要在堆中聲明connfd作爲變量?如果它被聲明爲局部變量可能會發生什麼問題?
這是代碼,以使每個線程(在main()函數)
int* connfd;
pthread_t thread_id;
int client_sock
while (1)
{
connfd = malloc(sizeof(int));
*connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &clilen);
if(pthread_create(&thread_id , NULL , handle_client , (void*)&client_sock) < 0)
{
perror("could not create thread");
return 1;
}
}
這是我hadle_client功能。
void* handle_client(void* connfd)
{
/* read a string sent by the client,
* print it and then send the string
* "Hello from the server" to the client*/
int sock = *(int*)connfd;
int read_size;
char *message , client_message[2000];
//Send some messages to the client
message = "Hello from the server\n";
write(sock , message , strlen(message));
while((read_size = recv(sock , client_message , 2000 , 0)) > 0)
{
//end of string marker
client_message[read_size] = '\0';
//Send the message back to client
puts(client_message);
//clear the message buffer
memset(client_message, 0, 2000);
}
if(read_size == 0)
{
puts("Client disconnected");
fflush(stdout);
}
else if(read_size == -1)
{
perror("recv failed");
}
free(connfd);
return NULL;
}
注意到在你的代碼中,你傳遞一個指向未初始化的自動'client_sock'的指針;那看起來不正確 –