我有一個小型的客戶機 - 服務器程序,並且我想在超過10秒的最大超時後關閉與客戶機的連接。我有一個報警和關閉連接,報警處理程序看起來像這樣的功能:在C客戶機服務器程序中處理超時
void closeClient() {
int nr = close(conn);
if (nr == 0)
printf("Client connection closed.\n");
else {
printf("Error while closing client connection. Error code: %d\n",errno);
exit(1);
}
exit(0); // Process ends after serving the client
}
void time_out(int signal) {
printf("Time out.\n");
char* msg = "Time out.Connection to server is closed\n\0";
send(conn, msg, strlen(msg),0);
closeClient(conn);
exit(1);
}
的問題是,在客戶端打印消息(「時間out.Connection到服務器關閉」)僅當它會嘗試將某些內容發送給服務器(連接已關閉後)。我無法弄清楚爲什麼。一些建議?
你永遠不會顯示調用time_out函數的代碼。 – YeenFei
就像這樣:'code' signal(SIGALRM,time_out); 報警(10); cod = recv(conn,&buf,sizeof(buf),0); boolean isNumber = validateNumber(buf); printf(「收到的字符串:%s \ n」,buf); 報警(0); //停止計時器 if(!isNumber){//服務器沒有收到有效整數 errorMsg =「請輸入一個有效的整數!\ n \ 0」; 012fprintf(「正在發送錯誤消息.. \ n」); (conn,errorMsg,strlen(errorMsg)+1,0); } else ..'code' – joanna