在linux的socket編程中,經常會遇到超時設置的問題,例如請求方如果在Ks內不發送數據則服務器要斷開連接停止服務。這裡我使用select的io復用實現超時5s設置,具體代碼片段如下:
fd_set fs; timeval tv; tv.tv_sec = 5; tv.tv_usec = 0; FD_ZERO(&fs); FD_SET(socket_fd,&fs); int ret = select(socket_fd+1,&fs,NULL,NULL,&tv); if(ret == -1){ fprintf(stderr, "socket_job:run:error.\n"); }else if(ret == 0){ fprintf(stderr, "socket_job:run:time out.\n"); }else{ if(FD_ISSET(socket_fd,&fs)){ int length = 1024*1024; char* buffer = new char[length]; memset(buffer,0,sizeof(char)*length); int n = recv(socket_fd,buffer,sizeof(char)*length,0); if(n > 0){ //deal msg buffer[length] = '\0'; search_collector* searcher = new search_collector(); string result(""); searcher->search(buffer,10,result); //send result,result must be end with \n int result_length = strlen(result.c_str()); ret = send(socket_fd,result.c_str(),result_length,0); int all_send = 0; while(ret > 0 && ret < result_length){ result_length -= ret; all_send += ret; ret = send(socket_fd,result.c_str()+all_send,result_length,0); } } delete[] buffer; } }