int sock, connected, bytes_received, true = 1;
struct sockaddr_in server_addr, client_addr;
int sin_size;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Socket");
exit(1);
}
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &true, sizeof (int)) == -1) {
perror("Setsockopt");
exit(1);
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(atoi(argv[1]));
server_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(server_addr.sin_zero), 8);
if (bind(sock, (struct sockaddr *) &server_addr, sizeof (struct sockaddr))
== -1) {
perror("Unable to bind");
exit(1);
}
if (listen(sock, 5) == -1) {
perror("Listen");
exit(1);
}
printf("\nTCPServer Waiting for client on port 5003");
fflush(stdout);
while (1)
{
pthread_t *child = (pthread_t *)malloc(sizeof(pthread_t));
sin_size = sizeof (struct sockaddr_in);
connected = accept(sock, (struct sockaddr *) &client_addr, &sin_size);
printf("\n I got a connection from (%s , %d)\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
pthread_create(child, NULL, interpretMessage, NULL);
free(child);
}
我的TCP服務器偵聽端口5003.當建立連接時,我想產生一個線程並運行函數interpretMessage。我有幾個關於這個問題...C中的多線程TCP服務器
1)我在調用malloc並在正確的地方免費嗎?
2)pthread_create被調用後,我的代碼是否立即跳轉到「free(child);」然後回到while循環的開始?
3)如果5人在同一確切的時間(如何運行的代碼產卵5個螺紋連接,會發生什麼?)
嗨,非常感謝您的回覆。爲簡單起見,我刪除了參數,因爲我將一個結構傳遞給了interpretMessage函數,我不想將任何人與結構的內容混淆。我明白我現在需要做什麼,非常感謝你! – Eddie 2011-02-22 23:33:17