hi there i’m working on a multithread Server (TCP) in C and i have a little issue about it. Everything works fine, more than one thread can connect to the server but whenever a client writes “exit” (which is a condition for a client when he/she writes “exit” string he/she goes to disconnect from the server) serves shutsdown itself also. So the communication through other threads get lost. However, logically it should be waiting for other clients even some current clients get disconnected. Here is a part of main and server is in a endless loop for waiting clients. hsock is id of socket belongs to server and csock is the id of clients.
main(){
.
.
.
while(1){
if(counter==0)
printf("waiting for a connection\n");
csock = (int*)malloc(sizeof(int));
if((*csock = accept( hsock, (struct sockaddr*)&sadr, &addr_size))!= -1){
printf("---------------------\nReceived connection from %s\n",inet_ntoa(sadr.sin_addr));
pthread_create(&thread_id,0,&SocketHandler, (void*)csock );
counter++;
}
else{
fprintf(stderr, "Error accepting %d\n", errno);
}
}// end while
.
.
.
return 0
}
As you can see whenever a client get disconnected, server should keep waiting for an another threads. On the other hand, this is the last part of SocketHandler function which is a thread function.
void* SocketHandler(void* csock){
.
.
.
printf("Client disconnected\n");
free(csock);
return 0;
}
After return 0 statement isn’t it necessary to return back to while(1) loop in main. I will be glad if you can help and thanks anyway
Threads run asynchronously once created, which means that the main thread (the one doing the
accept) should continue looping and be back to accepting new connections, whatever the child thread does.Some advices:
pthread_detachafter the create to let thread handle its own termination graciously.close(csock)before ending the thread.void *directly (but I guess that you will be passing more information than just the socket in a structure in a future version of your code).