2017-05-19 3 views
0

클라이언트가 서버에 데이터를 보내는 클라이언트 서버 연결이 있습니다.수신 기능의 소켓 시간 초과 설정

while (1) { 

    bzero(buffer, 256); 
    sleep(1); 

    n = read(sock, buffer); 
    if(n < 0) error("ERROR reading from socket"); 
    c = message[0]; 

    //do something 

}//close while loop 

난 단지 읽기 몇 초 동안 만 일어날 때까지 기다려야 할 문제 - 내 코드에서 클라이언트가 아무 것도 보내지 않는 경우, 뭔가를 읽을 수있는 서버를 기다리는 붙어됩니다.

읽기가 몇 초 만에 끝나기를 기다리는 방법은 무엇입니까?

+3

[읽기 함수 호출에서 시간 초과를 구현하는 방법?] (http://stackoverflow.com/questions/2917881/how-to-implement-a-timeout-in-read-function-call) – rtur

+0

@rtur IPC에서 읽기 때문에 작동하지 않을 것이라고 생각합니다. – CXB

+1

@CXB 어때 [this] (http://stackoverflow.com/questions/2876024/linux-is-there-a-read- 소켓에서 - recv - from - timeout) – Gaurav

답변

1

이 목적으로 select() api를 사용할 수 있습니다. 이 API에서는 초 및 마이크로 초 단위로 선택 API에서 시간을 언급 할 수 있습니다. 당신이 그것에 스택을 얻을하지 않으려면

+0

select를 사용해 보았지만 아무 것도 출력하지 않습니다. – CXB

+0

select api의 구문을 보여 줄 수 있습니까? – Amol

0

기본적으로 read 통화 시도는 비 블로킹으로 sock 변수를 선언하거나 제한 시간 (man select)로 select 기능을 사용했습니다 그래서 읽을 수 있습니다. 첫 번째 경우에는 몇 초를 기다릴 수 없지만 k 번을 읽은 다음 다시 시도 할 수 있습니다.

/* 
* Non-blocking socket solution 
* just put the read in a for-loop 
* if you want to read k times 
*/ 


#include <errno.h> 
#include <fcntl.h> 
#include <unistd.h> 

int r1; 
/*Setting the socket as non-blocking*/ 
int flags = fcntl(sock, F_GETFL, 0); 
fcntl(sock, F_SETFL, flags | O_NONBLOCK); 
errno = 0; /*If the read fails it sets errno*/ 
if((r1=read(sock,buf_in,N))== -1) { /*If the read returns an error*/ 
    if(errno != EAGAIN && errno != EWOULDBLOCK){ /*If the error is not caused by the non-blocking socket*/ 
       perror("Error in read\n"); 
       exit(EXIT_FAILURE); 
      } 
} 

다음은 선택 솔루션입니다 : 여기에 비 블로킹 소켓에 대한 예제가 당신의 소켓이

/* 
* Select solution. 
* This is not a complete solution but 
* it's almost everything you've to do 
*/ 


#include <errno.h> 
#include <fcntl.h> 
#include <unistd.h> 
#include <sys/select.h> 

#define SVC(r,c,e) \ 
    errno = 0; \ 
    if((r=c)==-1) { perror(e);exit(errno); } 

int r = 0; 
int fd_skt; 
fd_set rdset; 
fd_set set; 
struct timeval tv; /*Timer structure*/ 
int fd_num_max = 0; /*Maximum opened file descriptor*/ 
if(fd_skt > fd_num_max) fd_num_max = fd_skt; 
FD_ZERO(set); 
FD_SET(fd_skt,set); /*fd_skt is where you're waiting for new connection request*/ 
/*Setting the timer*/ 
tv.tv_sec = 0; 
tv.tv_usec = 200*1000; 
rdset = set; 
SVC(r,select((fd_num_max+1),(&rdset),NULL,NULL,&tv),"Unable to select\n");