您好在使用線程時有一點printf問題。問題是終端打印一個稍後應該打印的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"
後。它應該以相反的方式工作。我會很高興,如果你能幫助,並感謝反正
您可能需要考慮'fflush()'。您可能需要考慮['flockfile()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/flockfile.html)和'funlockfile()'。 –
問題在哪裏 - 我沒有看到:等待/接收,等待/接收,等待。這就是你編碼的方式,是我期望的輸出。接受線程啓動,等待,然後接收兩個連接,然後等待另一個連接。 –
@JonathanLeffler實際上把'fflush(stdout)'放在'printf(「正在等待一個連接\ n」)的上方和下方;'但仍然輸出相同 – quartaela