嗨,使用线程时 printf 有一点问题。问题是终端稍后打印一个 printf 语句,应该更早打印。这是我面临这个问题的部分。
.
.
.
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
.
.
.
这是线程使用的功能。
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;
}
每当客户端(线程)连接到服务器时,输出都是这样的。
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
当第一个客户端连接时,输出正常工作,但是当第二个客户端连接时,字符串"waiting for a connection"
在"Received connection"
. 那么它应该以对比的方式工作。如果你能提供帮助,我会很高兴,无论如何,谢谢