기본적으로 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");
[읽기 함수 호출에서 시간 초과를 구현하는 방법?] (http://stackoverflow.com/questions/2917881/how-to-implement-a-timeout-in-read-function-call) – rtur
@rtur IPC에서 읽기 때문에 작동하지 않을 것이라고 생각합니다. – CXB
@CXB 어때 [this] (http://stackoverflow.com/questions/2876024/linux-is-there-a-read- 소켓에서 - recv - from - timeout) – Gaurav