hi there a have a little problem with printf while using threads. problem is terminal prints one printf statement a little bit later which should be printed earlier. this is the part where i’m facing with this issue.
.
.
.
while(1){
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));
client_counter++;
pthread_create(&thread_id,0,&SocketHandler, (void*)csock );
}
else{
fprintf(stderr, "Error accepting %d\n", errno);
}
}// end while
.
.
.
and this is the function which threads’ use.
void* SocketHandler(void* lp){
int *csock = (int*)lp;
char buffer[1024];
int buffer_len = 1024;
int bytecount;
char* str_exit="exit";
while(1){
memset(buffer, 0, buffer_len);
if((bytecount = recv(*csock, buffer, buffer_len, 0))== -1){
fprintf(stderr, "Error receiving data %d\n", errno);
exit(0);
}
if(strcmp(buffer,str_exit)==0){
break;
}
printf("Received bytes %d\nReceived string \"%s\"\n", bytecount, buffer);
strcat(buffer, " SERVER ECHO");
if((bytecount = send(*csock, buffer, strlen(buffer), 0))== -1){
fprintf(stderr, "Error sending data %d\n", errno);
exit(0);
}
//printf("Sent bytes %d Sent String %s\n", bytecount,buffer);
}
printf("Client disconnected\n");
free(csock);
return 0;
}
and the output is like this whenever a client (thread) connects to the server.
waiting for a connection
---------------------
Received connection from 127.0.0.1
waiting for a connection
Client disconnected
---------------------
Received connection from 127.0.0.1
waiting for a connection
Client disconnected
when the first client connects the output works properly, but when the second one connects the string "waiting for a connection" comes after "Received connection". well it should work in contrast way. i will be glad if you can help and thanks anyway
There is no issue. Apart from the first time the loop is entered, ‘waiting for a connection’ will be the last thing printed by the accept thread after a client connects.
Put another way, this loop starts/ends at the accept() call except when entered for the first time. It is the first time through that is the ‘exception’, not the subsequent loops.